Add files via upload
diff --git a/caravel/gds/antenna_on_gds.tcl b/caravel/gds/antenna_on_gds.tcl
new file mode 100644
index 0000000..5f379c6
--- /dev/null
+++ b/caravel/gds/antenna_on_gds.tcl
@@ -0,0 +1,28 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+gds read $::env(DESIGN_IN_ANTENNA).gds
+select top cell
+extract do local
+extract no capacitance
+extract no coupling
+extract no resistance
+extract no adjust
+extract unique
+# extract warn all
+extract
+feedback save ./tmp/$::env(DESIGN_IN_ANTENNA)_ext2spice.antenna.feedback.txt
+antennacheck debug
+antennacheck
diff --git a/caravel/gds/drc_on_gds.tcl b/caravel/gds/drc_on_gds.tcl
new file mode 100644
index 0000000..8bb3035
--- /dev/null
+++ b/caravel/gds/drc_on_gds.tcl
@@ -0,0 +1,61 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+gds read $::env(DESIGN_IN_DRC).gds
+set fout [open ./tmp/$::env(DESIGN_IN_DRC).drc w]
+set oscale [cif scale out]
+set cell_name $::env(DESIGN_IN_DRC)
+magic::suspendall
+puts stdout "\[INFO\]: Loading $::env(DESIGN_IN_DRC)\n"
+flush stdout
+load $::env(DESIGN_IN_DRC)
+select top cell
+drc euclidean on
+drc style drc(full)
+drc check
+set drcresult [drc listall why]
+set count 0
+puts $fout "$::env(DESIGN_IN_DRC)"
+puts $fout "----------------------------------------"
+foreach {errtype coordlist} $drcresult {
+ puts $fout $errtype
+ puts $fout "----------------------------------------"
+ foreach coord $coordlist {
+ set bllx [expr {$oscale * [lindex $coord 0]}]
+ set blly [expr {$oscale * [lindex $coord 1]}]
+ set burx [expr {$oscale * [lindex $coord 2]}]
+ set bury [expr {$oscale * [lindex $coord 3]}]
+ set coords [format " %.3f %.3f %.3f %.3f" $bllx $blly $burx $bury]
+ puts $fout "$coords"
+ set count [expr {$count + 1} ]
+ }
+ puts $fout "----------------------------------------"
+}
+
+puts $fout "\[INFO\]: COUNT: $count"
+puts $fout "\[INFO\]: Should be divided by 3 or 4"
+
+puts $fout ""
+close $fout
+
+puts stdout "\[INFO\]: COUNT: $count"
+puts stdout "\[INFO\]: Should be divided by 3 or 4"
+puts stdout "\[INFO\]: DRC Checking DONE (./tmp/$::env(DESIGN_IN_DRC).drc)"
+flush stdout
+
+puts stdout "\[INFO\]: Saving mag view with DRC errors(./tmp/$::env(DESIGN_IN_DRC).drc.mag)"
+# WARNING: changes the name of the cell; keep as last step
+save ./tmp/$::env(DESIGN_IN_DRC).drc.drc.mag
+puts stdout "\[INFO\]: Saved"
diff --git a/caravel/gds/gds2mag-all.sh b/caravel/gds/gds2mag-all.sh
new file mode 100644
index 0000000..b9ca6f2
--- /dev/null
+++ b/caravel/gds/gds2mag-all.sh
@@ -0,0 +1,34 @@
+#!/bin/sh
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+
+
+gunzip *.gz
+mv sram_1rw1r_32_256_8_sky130_lp1.gds sram_1rw1r_32_256_8_sky130.gds
+
+o-gds2mag-mag.sh simple_por.gds
+o-gds2mag-mag.sh gpio_control_block.gds
+o-gds2mag-mag.sh digital_pll.gds
+o-gds2mag-mag.sh storage.gds
+o-gds2mag-mag.sh mgmt_core.gds
+o-gds2mag-mag.sh chip_io.gds
+o-gds2mag-mag.sh sram_1rw1r_32_256_8_sky130.gds
+
+mv -f *.mag ../mag
+
+gzip -9 storage.gds mgmt_core.gds chip_io.gds
+
+
diff --git a/caravel/gds/user_project.gds b/caravel/gds/user_project.gds
new file mode 100644
index 0000000..45ee031
--- /dev/null
+++ b/caravel/gds/user_project.gds
Binary files differ
diff --git a/caravel/gds/user_project_wrapper.gds.gz b/caravel/gds/user_project_wrapper.gds.gz
new file mode 100644
index 0000000..7146465
--- /dev/null
+++ b/caravel/gds/user_project_wrapper.gds.gz
Binary files differ
diff --git a/caravel/openlane/Makefile b/caravel/openlane/Makefile
new file mode 100644
index 0000000..6386c39
--- /dev/null
+++ b/caravel/openlane/Makefile
@@ -0,0 +1,85 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+
+BLOCKS = $(shell find * -maxdepth 0 -type d)
+CONFIG = $(foreach block,$(BLOCKS), ./$(block)/config.tcl)
+CLEAN = $(foreach block,$(BLOCKS), clean-$(block))
+
+OPENLANE_TAG ?= v0.14
+OPENLANE_IMAGE_NAME ?= efabless/openlane:$(OPENLANE_TAG)
+OPENLANE_BASIC_COMMAND = "cd /project/openlane && flow.tcl -design ./$* -save_path .. -save -tag $* -overwrite"
+OPENLANE_INTERACTIVE_COMMAND = "cd /project/openlane && flow.tcl -it -file ./$*/interactive.tcl"
+
+all: $(BLOCKS)
+
+$(CONFIG) :
+ @echo "Missing $@. Please create a configuration for that design"
+ @exit 1
+
+$(BLOCKS) : % : ./%/config.tcl FORCE
+ifeq ($(OPENLANE_ROOT),)
+ @echo "Please export OPENLANE_ROOT"
+ @exit 1
+endif
+ifeq ($(PDK_ROOT),)
+ @echo "Please export PDK_ROOT"
+ @exit 1
+endif
+ @echo "###############################################"
+ @sleep 1
+
+ @if [ -f ./$*/interactive.tcl ]; then\
+ docker run -it -v $(OPENLANE_ROOT):/openLANE_flow \
+ -v $(PDK_ROOT):$(PDK_ROOT) \
+ -v $(PWD)/..:/project \
+ -e PDK_ROOT=$(PDK_ROOT) \
+ -u $(shell id -u $(USER)):$(shell id -g $(USER)) \
+ $(OPENLANE_IMAGE_NAME) sh -c $(OPENLANE_INTERACTIVE_COMMAND);\
+ else\
+ docker run -it -v $(OPENLANE_ROOT):/openLANE_flow \
+ -v $(PDK_ROOT):$(PDK_ROOT) \
+ -v $(PWD)/..:/project \
+ -e PDK_ROOT=$(PDK_ROOT) \
+ -u $(shell id -u $(USER)):$(shell id -g $(USER)) \
+ $(OPENLANE_IMAGE_NAME) sh -c $(OPENLANE_BASIC_COMMAND);\
+ fi
+ mkdir -p ../signoff/$*/
+ cp $*/runs/$*/OPENLANE_VERSION ../signoff/$*/
+ cp $*/runs/$*/PDK_SOURCES ../signoff/$*/
+ cp $*/runs/$*/reports/final_summary_report.csv ../signoff/$*/
+
+.PHONY: openlane
+openlane:
+ifeq ($(OPENLANE_ROOT),)
+ @echo "Please export OPENLANE_ROOT"
+ @exit 1
+endif
+ git clone https://github.com/efabless/openlane.git --branch=$(OPENLANE_TAG) --depth=1 $(OPENLANE_ROOT) && \
+ cd $(OPENLANE_ROOT) && \
+ make openlane
+
+FORCE:
+
+clean:
+ @echo "Use clean_all to clean everything :)"
+
+clean_all: $(CLEAN)
+
+$(CLEAN): clean-% :
+ rm -rf runs/$*
+ rm -rf ../gds/$**
+ rm -rf ../mag/$**
+ rm -rf ../lef/$**
diff --git a/caravel/openlane/user_project_wrapper_empty/config.tcl b/caravel/openlane/user_project_wrapper_empty/config.tcl
new file mode 100644
index 0000000..8cea6cd
--- /dev/null
+++ b/caravel/openlane/user_project_wrapper_empty/config.tcl
@@ -0,0 +1,43 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+set script_dir [file dirname [file normalize [info script]]]
+source $script_dir/fixed_wrapper_cfgs.tcl
+
+set ::env(DESIGN_NAME) user_project_wrapper
+
+set ::env(FP_PDN_CHECK_NODES) 0
+
+# set ::env(PDN_CFG) $script_dir/pdn.tcl
+
+set ::env(GLB_RT_OBS) "met1 0 0 $::env(DIE_AREA),\
+ met2 0 0 $::env(DIE_AREA),\
+ met3 0 0 $::env(DIE_AREA),\
+ met4 0 0 $::env(DIE_AREA),\
+ met5 0 0 $::env(DIE_AREA)"
+
+set ::env(CLOCK_PORT) "user_clock2"
+set ::env(CLOCK_NET) "mprj.clk"
+
+set ::env(CLOCK_PERIOD) "10"
+
+set ::env(PL_OPENPHYSYN_OPTIMIZATIONS) 0
+set ::env(DIODE_INSERTION_STRATEGY) 0
+
+set ::env(MAGIC_WRITE_FULL_LEF) 1
+
+set ::env(VERILOG_FILES) "\
+ $script_dir/../../verilog/rtl/defines.v \
+ $script_dir/../../verilog/rtl/__user_project_wrapper.v"
diff --git a/caravel/openlane/user_project_wrapper_empty/fixed_wrapper_cfgs.tcl b/caravel/openlane/user_project_wrapper_empty/fixed_wrapper_cfgs.tcl
new file mode 100644
index 0000000..6893d94
--- /dev/null
+++ b/caravel/openlane/user_project_wrapper_empty/fixed_wrapper_cfgs.tcl
@@ -0,0 +1,60 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+# DON'T TOUCH THE FOLLOWING SECTIONS
+
+# This makes sure that the core rings are outside the boundaries
+# of your block.
+set ::env(MAGIC_ZEROIZE_ORIGIN) 0
+
+# Area Configurations. DON'T TOUCH.
+set ::env(FP_SIZING) absolute
+set ::env(DIE_AREA) "0 0 2920 3520"
+
+set ::env(RUN_CVC) 0
+
+# Pin Configurations. DON'T TOUCH
+set ::env(FP_PIN_ORDER_CFG) $script_dir/pin_order.cfg
+
+set ::unit 2.4
+set ::env(FP_IO_VEXTEND) [expr 2*$::unit]
+set ::env(FP_IO_HEXTEND) [expr 2*$::unit]
+set ::env(FP_IO_VLENGTH) $::unit
+set ::env(FP_IO_HLENGTH) $::unit
+
+set ::env(FP_IO_VTHICKNESS_MULT) 4
+set ::env(FP_IO_HTHICKNESS_MULT) 4
+
+# Power & Pin Configurations. DON'T TOUCH.
+set ::env(FP_PDN_CORE_RING) 1
+set ::env(FP_PDN_CORE_RING_VWIDTH) 3
+set ::env(FP_PDN_CORE_RING_HWIDTH) $::env(FP_PDN_CORE_RING_VWIDTH)
+set ::env(FP_PDN_CORE_RING_VOFFSET) 14
+set ::env(FP_PDN_CORE_RING_HOFFSET) $::env(FP_PDN_CORE_RING_VOFFSET)
+set ::env(FP_PDN_CORE_RING_VSPACING) 1.7
+set ::env(FP_PDN_CORE_RING_HSPACING) $::env(FP_PDN_CORE_RING_VSPACING)
+
+set ::env(FP_PDN_VWIDTH) 3
+set ::env(FP_PDN_HWIDTH) 3
+set ::env(FP_PDN_VOFFSET) 5
+set ::env(FP_PDN_HOFFSET) $::env(FP_PDN_VOFFSET)
+set ::env(FP_PDN_VPITCH) 180
+set ::env(FP_PDN_HPITCH) $::env(FP_PDN_VPITCH)
+set ::env(FP_PDN_VSPACING) [expr 5*$::env(FP_PDN_CORE_RING_VWIDTH)]
+set ::env(FP_PDN_HSPACING) [expr 5*$::env(FP_PDN_CORE_RING_HWIDTH)]
+
+set ::env(VDD_NETS) [list {vccd1} {vccd2} {vdda1} {vdda2}]
+set ::env(GND_NETS) [list {vssd1} {vssd2} {vssa1} {vssa2}]
+set ::env(SYNTH_USE_PG_PINS_DEFINES) "USE_POWER_PINS"
diff --git a/caravel/openlane/user_project_wrapper_empty/interactive.tcl b/caravel/openlane/user_project_wrapper_empty/interactive.tcl
new file mode 100644
index 0000000..059d439
--- /dev/null
+++ b/caravel/openlane/user_project_wrapper_empty/interactive.tcl
@@ -0,0 +1,71 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+package require openlane
+set script_dir [file dirname [file normalize [info script]]]
+
+prep -design $script_dir -tag user_project_wrapper_empty -overwrite
+set save_path $script_dir/../..
+
+verilog_elaborate
+
+init_floorplan
+
+# making it "empty"
+remove_nets -input $::env(CURRENT_DEF)
+remove_components -input $::env(CURRENT_DEF)
+
+place_io_ol
+
+# add_macro_obs \
+# -defFile $::env(CURRENT_DEF) \
+# -lefFile $::env(MERGED_LEF_UNPADDED) \
+# -obstruction core_obs \
+# -placementX $::env(FP_IO_HLENGTH) \
+# -placementY $::env(FP_IO_VLENGTH) \
+# -sizeWidth [expr [lindex $::env(DIE_AREA) 2]-$::env(FP_IO_HLENGTH)*2] \
+# -sizeHeight [expr [lindex $::env(DIE_AREA) 3]-$::env(FP_IO_VLENGTH)*2] \
+# -fixed 1 \
+# -layerNames "met1 met2 met3 met4 met5"
+
+# exec -ignorestderr openroad -exit $script_dir/gen_pdn.tcl
+
+apply_route_obs
+
+run_power_grid_generation
+
+# set_def $::env(pdn_tmp_file_tag).def
+
+run_magic
+
+save_views -lef_path $::env(magic_result_file_tag).lef \
+ -def_path $::env(CURRENT_DEF) \
+ -gds_path $::env(magic_result_file_tag).gds \
+ -mag_path $::env(magic_result_file_tag).mag \
+ -save_path $save_path \
+ -tag $::env(RUN_TAG)
+
+# produce "obstructed" LEF to be used for routing
+set gap 0.4
+set llx [expr [lindex $::env(DIE_AREA) 0]-$gap]
+set lly [expr [lindex $::env(DIE_AREA) 1]-$gap]
+set urx [expr [lindex $::env(DIE_AREA) 2]+$gap]
+set ury [expr [lindex $::env(DIE_AREA) 3]+$gap]
+exec python3 $::env(OPENLANE_ROOT)/scripts/rectify.py $llx $lly $urx $ury \
+ < $::env(magic_result_file_tag).lef \
+ | python3 $::env(OPENLANE_ROOT)/scripts/obs.py {*}$::env(DIE_AREA) li1 met1 met2 met3 \
+ | python3 $::env(OPENLANE_ROOT)/scripts/obs.py -42.88 -37.53 2962.50 3557.21 met4 met5 \
+ > $::env(magic_result_file_tag).obstructed.lef
+file copy -force $::env(magic_result_file_tag).obstructed.lef $save_path/lef
diff --git a/caravel/openlane/user_project_wrapper_empty/pdn.tcl b/caravel/openlane/user_project_wrapper_empty/pdn.tcl
new file mode 100644
index 0000000..99d74b1
--- /dev/null
+++ b/caravel/openlane/user_project_wrapper_empty/pdn.tcl
@@ -0,0 +1,51 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+# Power nets
+if { ! [info exists ::env(VDD_NET)] } {
+ set ::env(VDD_NET) $::env(VDD_PIN)
+}
+
+if { ! [info exists ::env(GND_NET)] } {
+ set ::env(GND_NET) $::env(GND_PIN)
+}
+
+set ::power_nets $::env(VDD_NET)
+set ::ground_nets $::env(GND_NET)
+
+
+pdngen::specify_grid stdcell {
+ name grid
+ core_ring {
+ $::env(FP_PDN_LOWER_LAYER) {width $::env(FP_PDN_CORE_RING_VWIDTH) spacing $::env(FP_PDN_CORE_RING_VSPACING) core_offset $::env(FP_PDN_CORE_RING_VOFFSET)}
+ $::env(FP_PDN_UPPER_LAYER) {width $::env(FP_PDN_CORE_RING_HWIDTH) spacing $::env(FP_PDN_CORE_RING_HSPACING) core_offset $::env(FP_PDN_CORE_RING_HOFFSET)}
+
+ }
+ rails {
+ }
+ straps {
+ met4 {width $::env(FP_PDN_VWIDTH) pitch $::env(FP_PDN_VPITCH) offset $::env(FP_PDN_VOFFSET)}
+ met5 {width $::env(FP_PDN_HWIDTH) pitch $::env(FP_PDN_HPITCH) offset $::env(FP_PDN_HOFFSET)}
+ }
+ connect {{met4 met5}}
+}
+
+set ::halo [expr min($::env(FP_HORIZONTAL_HALO), $::env(FP_VERTICAL_HALO))]
+
+# POWER or GROUND #Std. cell rails starting with power or ground rails at the bottom of the core area
+set ::rails_start_with "POWER" ;
+
+# POWER or GROUND #Upper metal stripes starting with power or ground rails at the left/bottom of the core area
+set ::stripes_start_with "POWER" ;
\ No newline at end of file
diff --git a/caravel/openlane/user_project_wrapper_empty/pin_order.cfg b/caravel/openlane/user_project_wrapper_empty/pin_order.cfg
new file mode 100644
index 0000000..90cde69
--- /dev/null
+++ b/caravel/openlane/user_project_wrapper_empty/pin_order.cfg
@@ -0,0 +1,156 @@
+#BUS_SORT
+#NR
+analog_io\[8\]
+io_in\[15\]
+io_out\[15\]
+io_oeb\[15\]
+analog_io\[9\]
+io_in\[16\]
+io_out\[16\]
+io_oeb\[16\]
+analog_io\[10\]
+io_in\[17\]
+io_out\[17\]
+io_oeb\[17\]
+analog_io\[11\]
+io_in\[18\]
+io_out\[18\]
+io_oeb\[18\]
+analog_io\[12\]
+io_in\[19\]
+io_out\[19\]
+io_oeb\[19\]
+analog_io\[13\]
+io_in\[20\]
+io_out\[20\]
+io_oeb\[20\]
+analog_io\[14\]
+io_in\[21\]
+io_out\[21\]
+io_oeb\[21\]
+analog_io\[15\]
+io_in\[22\]
+io_out\[22\]
+io_oeb\[22\]
+analog_io\[16\]
+io_in\[23\]
+io_out\[23\]
+io_oeb\[23\]
+
+#S
+wb_.*
+wbs_.*
+la_.*
+user_clock2
+user_irq.*
+
+#E
+io_in\[0\]
+io_out\[0\]
+io_oeb\[0\]
+io_in\[1\]
+io_out\[1\]
+io_oeb\[1\]
+io_in\[2\]
+io_out\[2\]
+io_oeb\[2\]
+io_in\[3\]
+io_out\[3\]
+io_oeb\[3\]
+io_in\[4\]
+io_out\[4\]
+io_oeb\[4\]
+io_in\[5\]
+io_out\[5\]
+io_oeb\[5\]
+io_in\[6\]
+io_out\[6\]
+io_oeb\[6\]
+analog_io\[0\]
+io_in\[7\]
+io_out\[7\]
+io_oeb\[7\]
+analog_io\[1\]
+io_in\[8\]
+io_out\[8\]
+io_oeb\[8\]
+analog_io\[2\]
+io_in\[9\]
+io_out\[9\]
+io_oeb\[9\]
+analog_io\[3\]
+io_in\[10\]
+io_out\[10\]
+io_oeb\[10\]
+analog_io\[4\]
+io_in\[11\]
+io_out\[11\]
+io_oeb\[11\]
+analog_io\[5\]
+io_in\[12\]
+io_out\[12\]
+io_oeb\[12\]
+analog_io\[6\]
+io_in\[13\]
+io_out\[13\]
+io_oeb\[13\]
+analog_io\[7\]
+io_in\[14\]
+io_out\[14\]
+io_oeb\[14\]
+
+#WR
+analog_io\[17\]
+io_in\[24\]
+io_out\[24\]
+io_oeb\[24\]
+analog_io\[18\]
+io_in\[25\]
+io_out\[25\]
+io_oeb\[25\]
+analog_io\[19\]
+io_in\[26\]
+io_out\[26\]
+io_oeb\[26\]
+analog_io\[20\]
+io_in\[27\]
+io_out\[27\]
+io_oeb\[27\]
+analog_io\[21\]
+io_in\[28\]
+io_out\[28\]
+io_oeb\[28\]
+analog_io\[22\]
+io_in\[29\]
+io_out\[29\]
+io_oeb\[29\]
+analog_io\[23\]
+io_in\[30\]
+io_out\[30\]
+io_oeb\[30\]
+analog_io\[24\]
+io_in\[31\]
+io_out\[31\]
+io_oeb\[31\]
+analog_io\[25\]
+io_in\[32\]
+io_out\[32\]
+io_oeb\[32\]
+analog_io\[26\]
+io_in\[33\]
+io_out\[33\]
+io_oeb\[33\]
+analog_io\[27\]
+io_in\[34\]
+io_out\[34\]
+io_oeb\[34\]
+analog_io\[28\]
+io_in\[35\]
+io_out\[35\]
+io_oeb\[35\]
+io_in\[36\]
+io_out\[36\]
+io_oeb\[36\]
+io_in\[37\]
+io_out\[37\]
+io_oeb\[37\]
diff --git a/caravel/scripts/check_density.py b/caravel/scripts/check_density.py
new file mode 100644
index 0000000..25f44ba
--- /dev/null
+++ b/caravel/scripts/check_density.py
@@ -0,0 +1,616 @@
+#!/usr/bin/env python3
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+#
+# check_density.py ---
+#
+# Run density checks on the final (filled) GDS.
+#
+
+import sys
+import os
+import re
+import select
+import subprocess
+
+def usage():
+ print("Usage:")
+ print("check_density.py [<path_to_project>] [-keep]")
+ print("")
+ print("where:")
+ print(" <path_to_project> is the path to the project top level directory.")
+ print("")
+ print(" If <path_to_project> is not given, then it is assumed to be the cwd.")
+ print(" If '-keep' is specified, then keep the check script.")
+ return 0
+
+
+if __name__ == '__main__':
+
+ optionlist = []
+ arguments = []
+
+ debugmode = False
+ keepmode = False
+
+ for option in sys.argv[1:]:
+ if option.find('-', 0) == 0:
+ optionlist.append(option)
+ else:
+ arguments.append(option)
+
+ if len(arguments) > 1:
+ print("Wrong number of arguments given to check_density.py.")
+ usage()
+ sys.exit(0)
+
+ if len(arguments) == 1:
+ user_project_path = arguments[0]
+ else:
+ user_project_path = os.getcwd()
+
+ # Check for valid user path
+
+ if not os.path.isdir(user_project_path):
+ print('Error: Project path "' + user_project_path + '" does not exist or is not readable.')
+ sys.exit(1)
+
+ # Check for valid user ID
+ user_id_value = None
+ if os.path.isfile(user_project_path + '/info.yaml'):
+ with open(user_project_path + '/info.yaml', 'r') as ifile:
+ infolines = ifile.read().splitlines()
+ for line in infolines:
+ kvpair = line.split(':')
+ if len(kvpair) == 2:
+ key = kvpair[0].strip()
+ value = kvpair[1].strip()
+ if key == 'project_id':
+ user_id_value = value.strip('"\'')
+ break
+
+ if user_id_value:
+ project = 'caravel'
+ project_with_id = 'caravel_' + user_id_value
+ else:
+ print('Error: No project_id found in info.yaml file.')
+ sys.exit(1)
+
+ if '-debug' in optionlist:
+ debugmode = True
+ if '-keep' in optionlist:
+ keepmode = True
+
+ magpath = user_project_path + '/mag'
+ rcfile = magpath + '/.magicrc'
+
+ with open(magpath + '/check_density.tcl', 'w') as ofile:
+ print('#!/bin/env wish', file=ofile)
+ print('crashbackups stop', file=ofile)
+ print('drc off', file=ofile)
+ print('snap internal', file=ofile)
+
+ print('set starttime [orig_clock format [orig_clock seconds] -format "%D %T"]', file=ofile)
+ print('puts stdout "Started reading GDS: $starttime"', file=ofile)
+ print('', file=ofile)
+ print('flush stdout', file=ofile)
+ print('update idletasks', file=ofile)
+
+ # Read final project from .gds
+ print('gds readonly true', file=ofile)
+ print('gds rescale false', file=ofile)
+ print('gds read ../gds/' + project_with_id + '.gds', file=ofile)
+ print('', file=ofile)
+
+ print('set midtime [orig_clock format [orig_clock seconds] -format "%D %T"]', file=ofile)
+ print('puts stdout "Starting density checks: $midtime"', file=ofile)
+ print('', file=ofile)
+ print('flush stdout', file=ofile)
+ print('update idletasks', file=ofile)
+
+ # Get step box dimensions (700um for size and 70um for FOM step)
+ # Use 350um for stepping on other layers.
+ print('box values 0 0 0 0', file=ofile)
+ # print('box size 700um 700um', file=ofile)
+ # print('set stepbox [box values]', file=ofile)
+ # print('set stepwidth [lindex $stepbox 2]', file=ofile)
+ # print('set stepheight [lindex $stepbox 3]', file=ofile)
+
+ print('box size 70um 70um', file=ofile)
+ print('set stepbox [box values]', file=ofile)
+ print('set stepsizex [lindex $stepbox 2]', file=ofile)
+ print('set stepsizey [lindex $stepbox 3]', file=ofile)
+
+ print('select top cell', file=ofile)
+ print('expand', file=ofile)
+
+ # Modify the box to be inside the seal ring area (shrink 5um)
+ print('box grow c -5um', file=ofile)
+ print('set fullbox [box values]', file=ofile)
+
+ print('set xmax [lindex $fullbox 2]', file=ofile)
+ print('set xmin [lindex $fullbox 0]', file=ofile)
+ print('set fullwidth [expr {$xmax - $xmin}]', file=ofile)
+ print('set xtiles [expr {int(ceil(($fullwidth + 0.0) / $stepsizex))}]', file=ofile)
+ print('set ymax [lindex $fullbox 3]', file=ofile)
+ print('set ymin [lindex $fullbox 1]', file=ofile)
+ print('set fullheight [expr {$ymax - $ymin}]', file=ofile)
+ print('set ytiles [expr {int(ceil(($fullheight + 0.0) / $stepsizey))}]', file=ofile)
+ print('box size $stepsizex $stepsizey', file=ofile)
+ print('set xbase [lindex $fullbox 0]', file=ofile)
+ print('set ybase [lindex $fullbox 1]', file=ofile)
+ print('', file=ofile)
+
+ print('puts stdout "XTILES: $xtiles"', file=ofile)
+ print('puts stdout "YTILES: $ytiles"', file=ofile)
+ print('', file=ofile)
+
+ # Need to know what fraction of a full tile is the last row and column
+ print('set xfrac [expr {($xtiles * $stepsizex - $fullwidth + 0.0) / $stepsizex}]', file=ofile)
+ print('set yfrac [expr {($ytiles * $stepsizey - $fullheight + 0.0) / $stepsizey}]', file=ofile)
+ print('puts stdout "XFRAC: $xfrac"', file=ofile)
+ print('puts stdout "YFRAC: $yfrac"', file=ofile)
+
+ print('cif ostyle density', file=ofile)
+
+ # Process density at steps. For efficiency, this is done in 70x70 um
+ # areas, dumped to a file, and then aggregated into the 700x700 areas.
+
+ print('for {set y 0} {$y < $ytiles} {incr y} {', file=ofile)
+ print(' for {set x 0} {$x < $xtiles} {incr x} {', file=ofile)
+ print(' set xlo [expr $xbase + $x * $stepsizex]', file=ofile)
+ print(' set ylo [expr $ybase + $y * $stepsizey]', file=ofile)
+ print(' set xhi [expr $xlo + $stepsizex]', file=ofile)
+ print(' set yhi [expr $ylo + $stepsizey]', file=ofile)
+ print(' box values $xlo $ylo $xhi $yhi', file=ofile)
+
+ # Flatten this area
+ print(' flatten -dobbox -nolabels tile', file=ofile)
+ print(' load tile', file=ofile)
+ print(' select top cell', file=ofile)
+
+ # Run density check for each layer
+ print(' puts stdout "Density results for tile x=$x y=$y"', file=ofile)
+
+ print(' set fdens [cif list cover fom_all]', file=ofile)
+ print(' set pdens [cif list cover poly_all]', file=ofile)
+ print(' set ldens [cif list cover li_all]', file=ofile)
+ print(' set m1dens [cif list cover m1_all]', file=ofile)
+ print(' set m2dens [cif list cover m2_all]', file=ofile)
+ print(' set m3dens [cif list cover m3_all]', file=ofile)
+ print(' set m4dens [cif list cover m4_all]', file=ofile)
+ print(' set m5dens [cif list cover m5_all]', file=ofile)
+ print(' puts stdout "FOM: $fdens"', file=ofile)
+ print(' puts stdout "POLY: $pdens"', file=ofile)
+ print(' puts stdout "LI1: $ldens"', file=ofile)
+ print(' puts stdout "MET1: $m1dens"', file=ofile)
+ print(' puts stdout "MET2: $m2dens"', file=ofile)
+ print(' puts stdout "MET3: $m3dens"', file=ofile)
+ print(' puts stdout "MET4: $m4dens"', file=ofile)
+ print(' puts stdout "MET5: $m5dens"', file=ofile)
+ print(' flush stdout', file=ofile)
+ print(' update idletasks', file=ofile)
+
+ print(' load ' + project_with_id, file=ofile)
+ print(' cellname delete tile', file=ofile)
+
+ print(' }', file=ofile)
+ print('}', file=ofile)
+
+ print('set endtime [orig_clock format [orig_clock seconds] -format "%D %T"]', file=ofile)
+ print('puts stdout "Ended: $endtime"', file=ofile)
+ print('', file=ofile)
+
+
+ myenv = os.environ.copy()
+ # Real views are necessary for the DRC checks
+ myenv['MAGTYPE'] = 'mag'
+
+ print('Running density checks on file ' + project_with_id + '.gds', flush=True)
+
+ mproc = subprocess.Popen(['magic', '-dnull', '-noconsole',
+ '-rcfile', rcfile, magpath + '/check_density.tcl'],
+ stdin = subprocess.DEVNULL,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.PIPE,
+ cwd = magpath,
+ env = myenv,
+ universal_newlines = True)
+
+ # Use signal to poll the process and generate any output as it arrives
+
+ dlines = []
+
+ while mproc:
+ status = mproc.poll()
+ if status != None:
+ try:
+ output = mproc.communicate(timeout=1)
+ except ValueError:
+ print('Magic forced stop, status ' + str(status))
+ sys.exit(1)
+ else:
+ outlines = output[0]
+ errlines = output[1]
+ for line in outlines.splitlines():
+ dlines.append(line)
+ print(line)
+ for line in errlines.splitlines():
+ print(line)
+ print('Magic exited with status ' + str(status))
+ if int(status) != 0:
+ sys.exit(int(status))
+ else:
+ break
+ else:
+ n = 0
+ while True:
+ n += 1
+ if n > 100:
+ n = 0
+ status = mproc.poll()
+ if status != None:
+ break
+ sresult = select.select([mproc.stdout, mproc.stderr], [], [], 0.5)[0]
+ if mproc.stdout in sresult:
+ outstring = mproc.stdout.readline().strip()
+ dlines.append(outstring)
+ print(outstring)
+ elif mproc.stderr in sresult:
+ outstring = mproc.stderr.readline().strip()
+ print(outstring)
+ else:
+ break
+
+ fomfill = []
+ polyfill = []
+ lifill = []
+ met1fill = []
+ met2fill = []
+ met3fill = []
+ met4fill = []
+ met5fill = []
+ xtiles = 0
+ ytiles = 0
+ xfrac = 0.0
+ yfrac = 0.0
+
+ for line in dlines:
+ dpair = line.split(':')
+ if len(dpair) == 2:
+ layer = dpair[0]
+ try:
+ density = float(dpair[1].strip())
+ except:
+ continue
+ if layer == 'FOM':
+ fomfill.append(density)
+ elif layer == 'POLY':
+ polyfill.append(density)
+ elif layer == 'LI1':
+ lifill.append(density)
+ elif layer == 'MET1':
+ met1fill.append(density)
+ elif layer == 'MET2':
+ met2fill.append(density)
+ elif layer == 'MET3':
+ met3fill.append(density)
+ elif layer == 'MET4':
+ met4fill.append(density)
+ elif layer == 'MET5':
+ met5fill.append(density)
+ elif layer == 'XTILES':
+ xtiles = int(dpair[1].strip())
+ elif layer == 'YTILES':
+ ytiles = int(dpair[1].strip())
+ elif layer == 'XFRAC':
+ xfrac = float(dpair[1].strip())
+ elif layer == 'YFRAC':
+ yfrac = float(dpair[1].strip())
+
+ if ytiles == 0 or xtiles == 0:
+ print('Failed to read XTILES or YTILES from output.')
+ sys.exit(1)
+
+ total_tiles = (ytiles - 9) * (xtiles - 9)
+
+ print('')
+ print('Density results (total tiles = ' + str(total_tiles) + '):')
+
+ # For FOM, step at 70um intervals (same as 70um check area)
+ fomstep = 1
+
+ # For poly, step only at 700um intervals (10 * 70um check area)
+ polystep = 10
+
+ # For all metals, step only at 350um intervals (5 * 70um check area)
+ metalstep = 5
+
+ # Full areas are 10 x 10 tiles = 100. But the right and top sides are
+ # not full tiles, so the full area must be prorated.
+
+ sideadjust = 90.0 + (10.0 * xfrac)
+ topadjust = 90.0 + (10.0 * yfrac)
+ corneradjust = 81.0 + (9.0 * xfrac) + (9.0 * yfrac) + (xfrac * yfrac)
+
+ print('')
+ print('FOM Density:')
+ for y in range(0, ytiles - 9, fomstep):
+ if y == ytiles - 10:
+ atotal = topadjust
+ else:
+ atotal = 100.0
+ for x in range(0, xtiles - 9, fomstep):
+ if x == xtiles - 10:
+ if y == ytiles - 10:
+ atotal = corneradjust
+ else:
+ atotal = sideadjust
+ fomaccum = 0
+ for w in range(y, y + 10):
+ base = xtiles * w + x
+ fomaccum += sum(fomfill[base : base + 10])
+
+ fomaccum /= atotal
+ print('Tile (' + str(x) + ', ' + str(y) + '): ' + str(fomaccum))
+ if fomaccum < 0.33:
+ print('***Error: FOM Density < 33%')
+ elif fomaccum > 0.57:
+ print('***Error: FOM Density > 57%')
+
+ print('')
+ print('POLY Density:')
+ for y in range(0, ytiles - 9, polystep):
+ if y == ytiles - 10:
+ atotal = topadjust
+ else:
+ atotal = 100.0
+ for x in range(0, xtiles - 9, polystep):
+ if x == xtiles - 10:
+ if y == ytiles - 10:
+ atotal = corneradjust
+ else:
+ atotal = sideadjust
+ polyaccum = 0
+ for w in range(y, y + 10):
+ base = xtiles * w + x
+ polyaccum += sum(polyfill[base : base + 10])
+
+ polyaccum /= atotal
+ print('Tile (' + str(x) + ', ' + str(y) + '): ' + str(polyaccum))
+
+ print('')
+ print('LI Density:')
+ for y in range(0, ytiles - 9, metalstep):
+ if y == ytiles - 10:
+ atotal = topadjust
+ else:
+ atotal = 100.0
+ for x in range(0, xtiles - 9, metalstep):
+ if x == xtiles - 10:
+ if y == ytiles - 10:
+ atotal = corneradjust
+ else:
+ atotal = sideadjust
+ liaccum = 0
+ for w in range(y, y + 10):
+ base = xtiles * w + x
+ liaccum += sum(lifill[base : base + 10])
+
+ liaccum /= atotal
+ print('Tile (' + str(x) + ', ' + str(y) + '): ' + str(liaccum))
+ if liaccum < 0.35:
+ print('***Error: LI Density < 35%')
+ elif liaccum > 0.60:
+ print('***Error: LI Density > 60%')
+
+ print('')
+ print('MET1 Density:')
+ for y in range(0, ytiles - 9, metalstep):
+ if y == ytiles - 10:
+ atotal = topadjust
+ else:
+ atotal = 100.0
+ for x in range(0, xtiles - 9, metalstep):
+ if x == xtiles - 10:
+ if y == ytiles - 10:
+ atotal = corneradjust
+ else:
+ atotal = sideadjust
+ met1accum = 0
+ for w in range(y, y + 10):
+ base = xtiles * w + x
+ met1accum += sum(met1fill[base : base + 10])
+
+ met1accum /= atotal
+ print('Tile (' + str(x) + ', ' + str(y) + '): ' + str(met1accum))
+ if met1accum < 0.35:
+ print('***Error: MET1 Density < 35%')
+ elif met1accum > 0.60:
+ print('***Error: MET1 Density > 60%')
+
+ print('')
+ print('MET2 Density:')
+ for y in range(0, ytiles - 9, metalstep):
+ if y == ytiles - 10:
+ atotal = topadjust
+ else:
+ atotal = 100.0
+ for x in range(0, xtiles - 9, metalstep):
+ if x == xtiles - 10:
+ if y == ytiles - 10:
+ atotal = corneradjust
+ else:
+ atotal = sideadjust
+ met2accum = 0
+ for w in range(y, y + 10):
+ base = xtiles * w + x
+ met2accum += sum(met2fill[base : base + 10])
+
+ met2accum /= atotal
+ print('Tile (' + str(x) + ', ' + str(y) + '): ' + str(met2accum))
+ if met2accum < 0.35:
+ print('***Error: MET2 Density < 35%')
+ elif met2accum > 0.60:
+ print('***Error: MET2 Density > 60%')
+
+ print('')
+ print('MET3 Density:')
+ for y in range(0, ytiles - 9, metalstep):
+ if y == ytiles - 10:
+ atotal = topadjust
+ else:
+ atotal = 100.0
+ for x in range(0, xtiles - 9, metalstep):
+ if x == xtiles - 10:
+ if y == ytiles - 10:
+ atotal = corneradjust
+ else:
+ atotal = sideadjust
+ met3accum = 0
+ for w in range(y, y + 10):
+ base = xtiles * w + x
+ met3accum += sum(met3fill[base : base + 10])
+
+ met3accum /= atotal
+ print('Tile (' + str(x) + ', ' + str(y) + '): ' + str(met3accum))
+ if met3accum < 0.35:
+ print('***Error: MET3 Density < 35%')
+ elif met3accum > 0.60:
+ print('***Error: MET3 Density > 60%')
+
+ print('')
+ print('MET4 Density:')
+ for y in range(0, ytiles - 9, metalstep):
+ if y == ytiles - 10:
+ atotal = topadjust
+ else:
+ atotal = 100.0
+ for x in range(0, xtiles - 9, metalstep):
+ if x == xtiles - 10:
+ if y == ytiles - 10:
+ atotal = corneradjust
+ else:
+ atotal = sideadjust
+ met4accum = 0
+ for w in range(y, y + 10):
+ base = xtiles * w + x
+ met4accum += sum(met4fill[base : base + 10])
+
+ met4accum /= atotal
+ print('Tile (' + str(x) + ', ' + str(y) + '): ' + str(met4accum))
+ if met4accum < 0.35:
+ print('***Error: MET4 Density < 35%')
+ elif met4accum > 0.60:
+ print('***Error: MET4 Density > 60%')
+
+ print('')
+ print('MET5 Density:')
+ for y in range(0, ytiles - 9, metalstep):
+ if y == ytiles - 10:
+ atotal = topadjust
+ else:
+ atotal = 100.0
+ for x in range(0, xtiles - 9, metalstep):
+ if x == xtiles - 10:
+ if y == ytiles - 10:
+ atotal = corneradjust
+ else:
+ atotal = sideadjust
+ met5accum = 0
+ for w in range(y, y + 10):
+ base = xtiles * w + x
+ met5accum += sum(met5fill[base : base + 10])
+
+ met5accum /= atotal
+ print('Tile (' + str(x) + ', ' + str(y) + '): ' + str(met5accum))
+ if met5accum < 0.45:
+ print('***Error: MET5 Density < 45%')
+ elif met5accum > 0.76:
+ print('***Error: MET5 Density > 76%')
+
+ print('')
+ print('Whole-chip density results:')
+
+ atotal = ((xtiles - 1.0) * (ytiles - 1.0)) + ((ytiles - 1.0) * xfrac) + ((xtiles - 1.0) * yfrac) + (xfrac * yfrac)
+
+ fomaccum = sum(fomfill) / atotal
+ print('')
+ print('FOM Density: ' + str(fomaccum))
+ if fomaccum < 0.33:
+ print('***Error: FOM Density < 33%')
+ elif fomaccum > 0.57:
+ print('***Error: FOM Density > 57%')
+
+ polyaccum = sum(polyfill) / atotal
+ print('')
+ print('POLY Density: ' + str(polyaccum))
+
+ liaccum = sum(lifill) / atotal
+ print('')
+ print('LI Density: ' + str(liaccum))
+ if liaccum < 0.35:
+ print('***Error: LI Density < 35%')
+ elif liaccum > 0.60:
+ print('***Error: LI Density > 60%')
+
+ met1accum = sum(met1fill) / atotal
+ print('')
+ print('MET1 Density: ' + str(met1accum))
+ if met1accum < 0.35:
+ print('***Error: MET1 Density < 35%')
+ elif met1accum > 0.60:
+ print('***Error: MET1 Density > 60%')
+
+ met2accum = sum(met2fill) / atotal
+ print('')
+ print('MET2 Density: ' + str(met2accum))
+ if met2accum < 0.35:
+ print('***Error: MET2 Density < 35%')
+ elif met2accum > 0.60:
+ print('***Error: MET2 Density > 60%')
+
+ met3accum = sum(met3fill) / atotal
+ print('')
+ print('MET3 Density: ' + str(met3accum))
+ if met3accum < 0.35:
+ print('***Error: MET3 Density < 35%')
+ elif met3accum > 0.60:
+ print('***Error: MET3 Density > 60%')
+
+ met4accum = sum(met4fill) / atotal
+ print('')
+ print('MET4 Density: ' + str(met4accum))
+ if met4accum < 0.35:
+ print('***Error: MET4 Density < 35%')
+ elif met4accum > 0.60:
+ print('***Error: MET4 Density > 60%')
+
+ met5accum = sum(met5fill) / atotal
+ print('')
+ print('MET5 Density: ' + str(met5accum))
+ if met5accum < 0.45:
+ print('***Error: MET5 Density < 45%')
+ elif met5accum > 0.76:
+ print('***Error: MET5 Density > 76%')
+
+ if not keepmode:
+ if os.path.isfile(magpath + '/check_density.tcl'):
+ os.remove(magpath + '/check_density.tcl')
+
+ print('')
+ print('Done!')
+ sys.exit(0)
diff --git a/caravel/scripts/compositor.py b/caravel/scripts/compositor.py
new file mode 100644
index 0000000..8e6ceb5
--- /dev/null
+++ b/caravel/scripts/compositor.py
@@ -0,0 +1,246 @@
+#!/usr/bin/env python3
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+#
+# compositor.py ---
+#
+# Compose the final GDS for caravel from the caravel GDS, seal ring
+# GDS, and fill GDS.
+#
+
+import sys
+import os
+import re
+import subprocess
+
+def usage():
+ print("Usage:")
+ print("compositor.py [<user_id_value>] [<path_to_project>] [<path_to_mag_dir>] [<path_to_gds_dir] [-keep]")
+ print("")
+ print("where:")
+ print(" <user_id_value> is a character string of eight hex digits, and")
+ print(" <path_to_project> is the path to the project top level directory.")
+ print(" <path_to_mag_dir> is the path to the mag directory.")
+ print(" <path_to_gds_dir> is the path to the gds directory.")
+ print("")
+ print(" If <user_id_value> is not given, then it must exist in the info.yaml file.")
+ print(" If <path_to_project> is not given, then it is assumed to be the cwd.")
+ print(" If <path_to_mag_dir> is not given, then it is assumed to be the <path_to_project>/tmp.")
+ print(" If <path_to_gds_dir> is not given, then it is assumed to be the <path_to_project>/gds.")
+ print(" If '-keep' is specified, then keep the generation script.")
+ return 0
+
+if __name__ == '__main__':
+
+ optionlist = []
+ arguments = []
+
+ debugmode = False
+ keepmode = False
+
+ for option in sys.argv[1:]:
+ if option.find('-', 0) == 0:
+ optionlist.append(option)
+ else:
+ arguments.append(option)
+
+ if len(arguments) > 4:
+ print("Wrong number of arguments given to compositor.py.")
+ usage()
+ sys.exit(0)
+
+ user_id_value = None
+ if len(arguments) > 0:
+ user_id_value = arguments[0]
+
+ # Convert to binary
+ try:
+ user_id_int = int('0x' + user_id_value, 0)
+ user_id_bits = '{0:032b}'.format(user_id_int)
+ except:
+ user_project_path = arguments[0]
+ user_id_value = None
+
+ if len(arguments) == 2 and user_project_path == None:
+ user_project_path = arguments[1]
+ mag_dir_path = user_project_path + "/mag"
+ gds_dir_path = "../gds"
+ if len(arguments) == 3 and user_project_path == None:
+ user_project_path = arguments[1]
+ mag_dir_path = arguments[2]
+ gds_dir_path = "../gds"
+ if len(arguments) == 4:
+ user_project_path = arguments[1]
+ mag_dir_path = arguments[2]
+ gds_dir_path = arguments[3]
+ elif len(arguments) == 3 and user_project_path != None:
+ mag_dir_path = arguments[1]
+ gds_dir_path = arguments[2]
+ else:
+ user_project_path = os.getcwd()
+ mag_dir_path = user_project_path + "/mag"
+ gds_dir_path = "../gds"
+
+ # Check for valid user path
+
+ if not os.path.isdir(user_project_path):
+ print('Error: Project path "' + user_project_path + '" does not exist or is not readable.')
+ sys.exit(1)
+
+ # Check for valid mag path
+
+ if not os.path.isdir(mag_dir_path):
+ print('Error: Mag directory path "' + mag_dir_path + '" does not exist or is not readable.')
+ sys.exit(1)
+
+ # Check for valid gds path
+
+ if not os.path.isdir(gds_dir_path):
+ print('Error: GDS directory path "' + gds_dir_path + '" does not exist or is not readable.')
+ sys.exit(1)
+
+ # Check for valid user ID
+ if not user_id_value:
+ if os.path.isfile(user_project_path + '/info.yaml'):
+ with open(user_project_path + '/info.yaml', 'r') as ifile:
+ infolines = ifile.read().splitlines()
+ for line in infolines:
+ kvpair = line.split(':')
+ if len(kvpair) == 2:
+ key = kvpair[0].strip()
+ value = kvpair[1].strip()
+ if key == 'project_id':
+ user_id_value = value.strip('"\'')
+ break
+
+ if user_id_value:
+ project = 'caravel'
+ project_with_id = 'caravel_' + user_id_value
+ user_id_decimal = str(int(user_id_value, 16))
+ else:
+ print('Error: No project_id found in info.yaml file.')
+ sys.exit(1)
+
+ if '-debug' in optionlist:
+ debugmode = True
+ if '-keep' in optionlist:
+ keepmode = True
+
+ magpath = mag_dir_path
+ rcfile = magpath + '/.magicrc'
+
+ gdspath = gds_dir_path
+
+ # The compositor script will create <project_with_id>.mag, but is uses
+ # "load", so the file must not already exist.
+
+ if os.path.isfile(magpath + '/' + project_with_id + '.mag'):
+ print('Error: File ' + project_with_id + '.mag exists already! Exiting. . .')
+ sys.exit(1)
+
+ with open(magpath + '/compose_final.tcl', 'w') as ofile:
+ print('#!/bin/env wish', file=ofile)
+ print('drc off', file=ofile)
+ # Set the random seed from the project ID
+ print('random seed ' + user_id_decimal, file=ofile)
+
+ # Read project from .mag but set GDS properties so that it points
+ # to the GDS file created by "make ship".
+ print('load ' + project + ' -dereference', file=ofile)
+ print('property GDS_FILE ' + gdspath + '/' + project + '.gds', file=ofile)
+ print('property GDS_START 0', file=ofile)
+ print('select top cell', file=ofile)
+ print('set bbox [box values]', file=ofile)
+
+ # Ceate a cell to represent the generated fill. There are
+ # no magic layers corresponding to the fill shape data, and
+ # it's gigabytes anyway, so we don't want to deal with any
+ # actual data. So it's just a placeholder.
+
+ print('load ' + project_with_id + '_fill_pattern -quiet', file=ofile)
+ print('snap internal', file=ofile)
+ print('box values {*}$bbox', file=ofile)
+ print('paint comment', file=ofile)
+ print('property GDS_FILE ' + gdspath + '/' + project_with_id + '_fill_pattern.gds', file=ofile)
+ print('property GDS_START 0', file=ofile)
+ print('property FIXED_BBOX "$bbox"', file=ofile)
+
+ # Create a new project top level and place the fill cell.
+ print('load ' + project_with_id + ' -quiet', file=ofile)
+ print('box values 0 0 0 0', file=ofile)
+ print('box position 6um 6um', file=ofile)
+ print('getcell ' + project + ' child 0 0', file=ofile)
+ print('getcell ' + project_with_id + '_fill_pattern child 0 0', file=ofile)
+
+ # Move existing origin to (6um, 6um) for seal ring placement
+ # print('move origin -6um -6um', file=ofile)
+
+ # Read in abstract view of seal ring
+ print('box position 0 0', file=ofile)
+ print('getcell advSeal_6um_gen', file=ofile)
+
+ # Write out completed project as "caravel_" + the user ID
+ print('save ' + project_with_id, file=ofile)
+
+ # Generate final GDS
+ print('puts stdout "Writing final GDS. . . "', file=ofile)
+ print('flush stdout', file=ofile)
+ print('gds undefined allow', file=ofile)
+ print('cif *hier write disable', file=ofile)
+ print('gds write ' + gdspath + '/' + project_with_id + '.gds', file=ofile)
+ print('quit -noprompt', file=ofile)
+
+ myenv = os.environ.copy()
+ # Abstract views are appropriate for final composition
+ myenv['MAGTYPE'] = 'maglef'
+
+ print('Building final GDS file ' + project_with_id + '.gds', flush=True)
+
+ mproc = subprocess.run(['magic', '-dnull', '-noconsole',
+ '-rcfile', rcfile, magpath + '/compose_final.tcl'],
+ stdin = subprocess.DEVNULL,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.PIPE,
+ cwd = magpath,
+ env = myenv,
+ universal_newlines = True)
+ if mproc.stdout:
+ for line in mproc.stdout.splitlines():
+ print(line)
+ if mproc.stderr:
+ # NOTE: Until there is a "load -quiet" option in magic, loading
+ # a new cell generates an error. This code ignores the error.
+ newlines = []
+ for line in mproc.stderr.splitlines():
+ if line.endswith("_fill_pattern.mag couldn't be read"):
+ continue
+ if line.startswith("No such file or directory"):
+ continue
+ else:
+ newlines.append(line)
+
+ if len(newlines) > 0:
+ print('Error message output from magic:')
+ for line in newlines:
+ print(line)
+ if mproc.returncode != 0:
+ print('ERROR: Magic exited with status ' + str(mproc.returncode))
+
+ if not keepmode:
+ os.remove(magpath + '/compose_final.tcl')
+
+ print('Done!')
+ exit(0)
diff --git a/caravel/scripts/count_lvs.py b/caravel/scripts/count_lvs.py
new file mode 100644
index 0000000..21b7771
--- /dev/null
+++ b/caravel/scripts/count_lvs.py
@@ -0,0 +1,132 @@
+#!/usr/bin/python3
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+#
+#---------------------------------------------------------
+# LVS failure check
+#
+# This is a Python script that parses the comp.json
+# output from netgen and reports on the number of
+# errors in the top-level netlist.
+#
+#---------------------------------------------------------
+# Written by Tim Edwards
+# efabless, inc.
+# Pulled from qflow GUI as standalone script Aug 20, 2018
+#---------------------------------------------------------
+
+import os
+import re
+import sys
+import json
+import argparse
+
+def count_LVS_failures(filename):
+ with open(filename, 'r') as cfile:
+ lvsdata = json.load(cfile)
+
+ # Count errors in the JSON file
+ failures = 0
+ devfail = 0
+ netfail = 0
+ pinfail = 0
+ propfail = 0
+ netdiff = 0
+ devdiff = 0
+ ncells = len(lvsdata)
+ for c in range(0, ncells):
+ cellrec = lvsdata[c]
+
+ if c == ncells - 1:
+ topcell = True
+ else:
+ topcell = False
+
+ # Most errors must only be counted for the top cell, because individual
+ # failing cells are flattened and the matching attempted again on the
+ # flattened netlist.
+
+ if topcell:
+ if 'devices' in cellrec:
+ devices = cellrec['devices']
+ devlist = [val for pair in zip(devices[0], devices[1]) for val in pair]
+ devpair = list(devlist[p:p + 2] for p in range(0, len(devlist), 2))
+ for dev in devpair:
+ c1dev = dev[0]
+ c2dev = dev[1]
+ diffdevs = abs(c1dev[1] - c2dev[1])
+ failures += diffdevs
+ devdiff += diffdevs
+
+ if 'nets' in cellrec:
+ nets = cellrec['nets']
+ diffnets = abs(nets[0] - nets[1])
+ failures += diffnets
+ netdiff += diffnets
+
+ if 'badnets' in cellrec:
+ badnets = cellrec['badnets']
+ failures += len(badnets)
+ netfail += len(badnets)
+
+ if 'badelements' in cellrec:
+ badelements = cellrec['badelements']
+ failures += len(badelements)
+ devfail += len(badelements)
+
+ if 'pins' in cellrec:
+ pins = cellrec['pins']
+ pinlist = [val for pair in zip(pins[0], pins[1]) for val in pair]
+ pinpair = list(pinlist[p:p + 2] for p in range(0, len(pinlist), 2))
+ for pin in pinpair:
+ # Avoid flagging global vs. local names, e.g., "gnd" vs. "gnd!,"
+ # and ignore case when comparing pins.
+ pin0 = re.sub('!$', '', pin[0].lower())
+ pin1 = re.sub('!$', '', pin[1].lower())
+ if pin0 != pin1:
+ failures += 1
+ pinfail += 1
+
+ # Property errors must be counted for every cell
+ if 'properties' in cellrec:
+ properties = cellrec['properties']
+ failures += len(properties)
+ propfail += len(properties)
+
+ return [failures, netfail, devfail, pinfail, propfail, netdiff, devdiff]
+
+if __name__ == '__main__':
+
+ parser = argparse.ArgumentParser(description='Parses netgen lvs')
+ parser.add_argument('--file', '-f', required=True)
+ args = parser.parse_args()
+ failures = count_LVS_failures(args.file)
+ total = failures[0]
+ if total > 0:
+ failed = True
+ print('LVS reports:')
+ print(' net count difference = ' + str(failures[5]))
+ print(' device count difference = ' + str(failures[6]))
+ print(' unmatched nets = ' + str(failures[1]))
+ print(' unmatched devices = ' + str(failures[2]))
+ print(' unmatched pins = ' + str(failures[3]))
+ print(' property failures = ' + str(failures[4]))
+ else:
+ print('LVS reports no net, device, pin, or property mismatches.')
+
+ print('')
+ print('Total errors = ' + str(total))
+
diff --git a/caravel/scripts/create-caravel-diagram.py b/caravel/scripts/create-caravel-diagram.py
new file mode 100644
index 0000000..bfb4e3c
--- /dev/null
+++ b/caravel/scripts/create-caravel-diagram.py
@@ -0,0 +1,126 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+import sys
+import os
+import subprocess
+from pathlib import Path
+import argparse
+from tempfile import mkstemp
+import re
+
+
+def remove_inouts(jsonpath, replacewith='input'):
+ """Replaces inouts with either input or output statements.
+
+ Netlistsvg does not parse inout ports as for now, so they need to be
+ replaced with either input or output to produce a diagram.
+
+ Parameters
+ ----------
+ jsonpath : str
+ Path to JSON file to fix
+ replacewith : str
+ The string to replace 'inout', can be 'input' or 'output'
+ """
+ assert replacewith in ['input', 'output']
+ with open(jsonpath, 'r') as withinouts:
+ lines = withinouts.readlines()
+ with open(jsonpath, 'w') as withoutinouts:
+ for line in lines:
+ withoutinouts.write(re.sub('inout', replacewith, line))
+
+
+def main(argv):
+ parser = argparse.ArgumentParser(argv[0])
+ parser.add_argument(
+ 'verilog_rtl_dir',
+ help="Path to the project's verilog/rtl directory",
+ type=Path)
+ parser.add_argument(
+ 'output',
+ help="Path to the output SVG file",
+ type=Path)
+ parser.add_argument(
+ '--num-iopads',
+ help='Number of iopads to render',
+ type=int,
+ default=38)
+ parser.add_argument(
+ '--yosys-executable',
+ help='Path to yosys executable',
+ type=Path,
+ default='yosys')
+ parser.add_argument(
+ '--netlistsvg-executable',
+ help='Path to netlistsvg executable',
+ type=Path,
+ default='netlistsvg')
+ parser.add_argument(
+ '--inouts-as',
+ help='To what kind of IO should inout ports be replaced',
+ choices=['input', 'output'],
+ default='input'
+ )
+
+ args = parser.parse_args(argv[1:])
+
+ fd, jsonpath = mkstemp(suffix='-yosys.json')
+ os.close(fd)
+
+ yosyscommand = [
+ f'{str(args.yosys_executable)}',
+ '-p',
+ 'read_verilog pads.v defines.v; ' +
+ 'read_verilog -lib -overwrite *.v; ' +
+ f'verilog_defines -DMPRJ_IO_PADS={args.num_iopads}; ' +
+ 'read_verilog -overwrite caravel.v; ' +
+ 'hierarchy -top caravel; ' +
+ 'proc; ' +
+ 'opt; ' +
+ f'write_json {jsonpath}; '
+ ]
+
+ result = subprocess.run(
+ yosyscommand,
+ cwd=args.verilog_rtl_dir,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT
+ )
+
+ exitcode = 0
+ if result.returncode != 0:
+ print(f'Failed to run: {" ".join(yosyscommand)}', file=sys.stderr)
+ print(result.stdout.decode())
+ exitcode = result.returncode
+ else:
+ # TODO once netlistsvg supports inout ports, this should be removed
+ remove_inouts(jsonpath, args.inouts_as)
+ command = f'{args.netlistsvg_executable} {jsonpath} -o {args.output}'
+ result = subprocess.run(
+ command.split(),
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT
+ )
+ if result.returncode != 0:
+ print(f'Failed to run: {command}', file=sys.stderr)
+ print(result.stdout.decode())
+ exitcode = result.returncode
+
+ os.unlink(jsonpath)
+ sys.exit(exitcode)
+
+
+if __name__ == '__main__':
+ sys.exit(main(sys.argv))
diff --git a/caravel/scripts/generate_fill.py b/caravel/scripts/generate_fill.py
new file mode 100644
index 0000000..d12024a
--- /dev/null
+++ b/caravel/scripts/generate_fill.py
@@ -0,0 +1,415 @@
+#!/usr/bin/env python3
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+#
+# generate_fill.py ---
+#
+# Run the fill generation on a layout top level.
+#
+
+import sys
+import os
+import re
+import glob
+import subprocess
+import multiprocessing
+
+def usage():
+ print("Usage:")
+ print("generate_fill.py [<user_id_value>] [<path_to_project>] [-keep] [-test] [-dist]")
+ print("")
+ print("where:")
+ print(" <user_id_value> is a character string of eight hex digits, and")
+ print(" <path_to_project> is the path to the project top level directory.")
+ print("")
+ print(" If <user_id_value> is not given, then it must exist in the info.yaml file.")
+ print(" If <path_to_project> is not given, then it is assumed to be the cwd.")
+ print(" If '-keep' is specified, then keep the generation script.")
+ print(" If '-test' is specified, then create but do not run the generation script.")
+ print(" If '-dist' is specified, then run distributed (multi-processing).")
+
+ return 0
+
+def makegds(file):
+ # Procedure for multiprocessing run only: Run the distributed processing
+ # script to load a .mag file of one flattened square area of the layout,
+ # and run the fill generator to produce a .gds file output from it.
+
+ magpath = os.path.split(file)[0]
+ filename = os.path.split(file)[1]
+
+ myenv = os.environ.copy()
+ myenv['MAGTYPE'] = 'mag'
+
+ mproc = subprocess.run(['magic', '-dnull', '-noconsole',
+ '-rcfile', rcfile, magpath + '/generate_fill_dist.tcl',
+ filename],
+ stdin = subprocess.DEVNULL,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.PIPE,
+ cwd = magpath,
+ env = myenv,
+ universal_newlines = True)
+ if mproc.stdout:
+ for line in mproc.stdout.splitlines():
+ print(line)
+ if mproc.stderr:
+ print('Error message output from magic:')
+ for line in mproc.stderr.splitlines():
+ print(line)
+ if mproc.returncode != 0:
+ print('ERROR: Magic exited with status ' + str(mproc.returncode))
+
+
+if __name__ == '__main__':
+
+ optionlist = []
+ arguments = []
+
+ debugmode = False
+ keepmode = False
+ testmode = False
+ distmode = False
+
+ for option in sys.argv[1:]:
+ if option.find('-', 0) == 0:
+ optionlist.append(option)
+ else:
+ arguments.append(option)
+
+ if len(arguments) > 2:
+ print("Wrong number of arguments given to generate_fill.py.")
+ usage()
+ sys.exit(1)
+
+ user_id_value = None
+ user_project_path = None
+
+ if len(arguments) > 0:
+ user_id_value = arguments[0]
+
+ # Convert to binary
+ try:
+ user_id_int = int('0x' + user_id_value, 0)
+ user_id_bits = '{0:032b}'.format(user_id_int)
+ except:
+ user_project_path = arguments[0]
+
+ if len(arguments) == 0:
+ user_project_path = os.getcwd()
+ elif len(arguments) == 2:
+ user_project_path = arguments[1]
+ elif user_project_path == None:
+ user_project_path = arguments[0]
+ else:
+ user_project_path = os.getcwd()
+
+ if not os.path.isdir(user_project_path):
+ print('Error: Project path "' + user_project_path + '" does not exist or is not readable.')
+ sys.exit(1)
+
+ # Check for valid user ID
+ if not user_id_value:
+ if os.path.isfile(user_project_path + '/info.yaml'):
+ with open(user_project_path + '/info.yaml', 'r') as ifile:
+ infolines = ifile.read().splitlines()
+ for line in infolines:
+ kvpair = line.split(':')
+ if len(kvpair) == 2:
+ key = kvpair[0].strip()
+ value = kvpair[1].strip()
+ if key == 'project_id':
+ user_id_value = value.strip('"\'')
+ break
+
+ project = 'caravel'
+ if user_id_value:
+ project_with_id = project + '_' + user_id_value
+ else:
+ print('Error: No project_id found in info.yaml file.')
+ sys.exit(1)
+
+ if '-debug' in optionlist:
+ debugmode = True
+ if '-keep' in optionlist:
+ keepmode = True
+ if '-test' in optionlist:
+ testmode = True
+ if '-dist' in optionlist:
+ distmode = True
+
+ magpath = user_project_path + '/mag'
+ rcfile = magpath + '/.magicrc'
+
+ if not os.path.isfile(rcfile):
+ rcfile = None
+
+ topdir = user_project_path
+ gdsdir = topdir + '/gds'
+ hasgdsdir = True if os.path.isdir(gdsdir) else False
+
+ ofile = open(magpath + '/generate_fill.tcl', 'w')
+
+ print('#!/bin/env wish', file=ofile)
+ print('drc off', file=ofile)
+ print('tech unlock *', file=ofile)
+ print('snap internal', file=ofile)
+ print('box values 0 0 0 0', file=ofile)
+ print('box size 700um 700um', file=ofile)
+ print('set stepbox [box values]', file=ofile)
+ print('set stepwidth [lindex $stepbox 2]', file=ofile)
+ print('set stepheight [lindex $stepbox 3]', file=ofile)
+ print('', file=ofile)
+ print('set starttime [orig_clock format [orig_clock seconds] -format "%D %T"]', file=ofile)
+ print('puts stdout "Started: $starttime"', file=ofile)
+ print('', file=ofile)
+ # Read the user project from GDS, as there is not necessarily a magic database file
+ # to go along with this.
+ # print('gds read ../gds/user_project_wrapper', file=ofile)
+ # Now read the full caravel project
+ # print('load ' + project + ' -dereference', file=ofile)
+ print('gds readonly true', file=ofile)
+ print('gds rescale false', file=ofile)
+ print('gds read ../gds/caravel', file=ofile)
+ print('select top cell', file=ofile)
+ print('expand', file=ofile)
+ if not distmode:
+ print('cif ostyle wafflefill(tiled)', file=ofile)
+ print('', file=ofile)
+ print('set fullbox [box values]', file=ofile)
+ print('set xmax [lindex $fullbox 2]', file=ofile)
+ print('set xmin [lindex $fullbox 0]', file=ofile)
+ print('set fullwidth [expr {$xmax - $xmin}]', file=ofile)
+ print('set xtiles [expr {int(ceil(($fullwidth + 0.0) / $stepwidth))}]', file=ofile)
+ print('set ymax [lindex $fullbox 3]', file=ofile)
+ print('set ymin [lindex $fullbox 1]', file=ofile)
+ print('set fullheight [expr {$ymax - $ymin}]', file=ofile)
+ print('set ytiles [expr {int(ceil(($fullheight + 0.0) / $stepheight))}]', file=ofile)
+ print('box size $stepwidth $stepheight', file=ofile)
+ print('set xbase [lindex $fullbox 0]', file=ofile)
+ print('set ybase [lindex $fullbox 1]', file=ofile)
+ print('', file=ofile)
+
+ # Break layout into tiles and process each separately
+ print('for {set y 0} {$y < $ytiles} {incr y} {', file=ofile)
+ print(' for {set x 0} {$x < $xtiles} {incr x} {', file=ofile)
+ print(' set xlo [expr $xbase + $x * $stepwidth]', file=ofile)
+ print(' set ylo [expr $ybase + $y * $stepheight]', file=ofile)
+ print(' set xhi [expr $xlo + $stepwidth]', file=ofile)
+ print(' set yhi [expr $ylo + $stepheight]', file=ofile)
+ print(' if {$xhi > $fullwidth} {set xhi $fullwidth}', file=ofile)
+ print(' if {$yhi > $fullheight} {set yhi $fullheight}', file=ofile)
+ print(' box values $xlo $ylo $xhi $yhi', file=ofile)
+ # The flattened area must be larger than the fill tile by >1.5um
+ print(' box grow c 1.6um', file=ofile)
+
+ # Flatten into a cell with a new name
+ print(' puts stdout "Flattening layout of tile x=$x y=$y. . . "', file=ofile)
+ print(' flush stdout', file=ofile)
+ print(' update idletasks', file=ofile)
+ print(' flatten -dobox -nolabels ' + project_with_id + '_fill_pattern_${x}_$y', file=ofile)
+ print(' load ' + project_with_id + '_fill_pattern_${x}_$y', file=ofile)
+ # Remove any GDS_FILE reference (there should not be any?)
+ print(' property GDS_FILE ""', file=ofile)
+ # Set boundary using comment layer, to the size of the step box
+ # This corresponds to the "topbox" rule in the wafflefill(tiled) style
+ print(' select top cell', file=ofile)
+ print(' erase comment', file=ofile)
+ print(' box values $xlo $ylo $xhi $yhi', file=ofile)
+ print(' paint comment', file=ofile)
+
+ if not distmode:
+ print(' puts stdout "Writing GDS. . . "', file=ofile)
+
+ print(' flush stdout', file=ofile)
+ print(' update idletasks', file=ofile)
+
+ if distmode:
+ print(' writeall force ' + project_with_id + '_fill_pattern_${x}_$y', file=ofile)
+ else:
+ print(' gds write ' + project_with_id + '_fill_pattern_${x}_$y.gds', file=ofile)
+ # Reload project top
+ print(' load ' + project, file=ofile)
+
+ # Remove last generated cell to save memory
+ print(' cellname delete ' + project_with_id + '_fill_pattern_${x}_$y', file=ofile)
+
+ print(' }', file=ofile)
+ print('}', file=ofile)
+
+ if distmode:
+ print('set ofile [open fill_gen_info.txt w]', file=ofile)
+ print('puts $ofile "$stepwidth"', file=ofile)
+ print('puts $ofile "$stepheight"', file=ofile)
+ print('puts $ofile "$xtiles"', file=ofile)
+ print('puts $ofile "$ytiles"', file=ofile)
+ print('puts $ofile "$xbase"', file=ofile)
+ print('puts $ofile "$ybase"', file=ofile)
+ print('close $ofile', file=ofile)
+ print('quit -noprompt', file=ofile)
+ ofile.close()
+
+ with open(magpath + '/generate_fill_dist.tcl', 'w') as ofile:
+ print('#!/bin/env wish', file=ofile)
+ print('drc off', file=ofile)
+ print('tech unlock *', file=ofile)
+ print('snap internal', file=ofile)
+ print('box values 0 0 0 0', file=ofile)
+ print('set filename [file root [lindex $argv $argc-1]]', file=ofile)
+ print('load $filename', file=ofile)
+ print('cif ostyle wafflefill(tiled)', file=ofile)
+ print('gds write [file root $filename].gds', file=ofile)
+ print('quit -noprompt', file=ofile)
+
+ ofile = open(magpath + '/generate_fill_final.tcl', 'w')
+ print('#!/bin/env wish', file=ofile)
+ print('drc off', file=ofile)
+ print('tech unlock *', file=ofile)
+ print('snap internal', file=ofile)
+ print('box values 0 0 0 0', file=ofile)
+
+ print('set ifile [open fill_gen_info.txt r]', file=ofile)
+ print('gets $ifile stepwidth', file=ofile)
+ print('gets $ifile stepheight', file=ofile)
+ print('gets $ifile xtiles', file=ofile)
+ print('gets $ifile ytiles', file=ofile)
+ print('gets $ifile xbase', file=ofile)
+ print('gets $ifile ybase', file=ofile)
+ print('close $ifile', file=ofile)
+ print('cif ostyle wafflefill(tiled)', file=ofile)
+
+ # Now create simple "fake" views of all the tiles.
+ print('gds readonly true', file=ofile)
+ print('gds rescale false', file=ofile)
+ print('for {set y 0} {$y < $ytiles} {incr y} {', file=ofile)
+ print(' for {set x 0} {$x < $xtiles} {incr x} {', file=ofile)
+ print(' set xlo [expr $xbase + $x * $stepwidth]', file=ofile)
+ print(' set ylo [expr $ybase + $y * $stepheight]', file=ofile)
+ print(' set xhi [expr $xlo + $stepwidth]', file=ofile)
+ print(' set yhi [expr $ylo + $stepheight]', file=ofile)
+ print(' load ' + project_with_id + '_fill_pattern_${x}_$y -quiet', file=ofile)
+ print(' box values $xlo $ylo $xhi $yhi', file=ofile)
+ print(' paint comment', file=ofile)
+ print(' property FIXED_BBOX "$xlo $ylo $xhi $yhi"', file=ofile)
+ print(' property GDS_FILE ' + project_with_id + '_fill_pattern_${x}_${y}.gds', file=ofile)
+ print(' property GDS_START 0', file=ofile)
+ print(' }', file=ofile)
+ print('}', file=ofile)
+
+ # Now tile everything back together
+ print('load ' + project_with_id + '_fill_pattern -quiet', file=ofile)
+ print('for {set y 0} {$y < $ytiles} {incr y} {', file=ofile)
+ print(' for {set x 0} {$x < $xtiles} {incr x} {', file=ofile)
+ print(' box values 0 0 0 0', file=ofile)
+ print(' getcell ' + project_with_id + '_fill_pattern_${x}_$y child 0 0', file=ofile)
+ print(' }', file=ofile)
+ print('}', file=ofile)
+
+ # And write final GDS
+ print('puts stdout "Writing final GDS"', file=ofile)
+
+ print('cif *hier write disable', file=ofile)
+ print('cif *array write disable', file=ofile)
+ if hasgdsdir:
+ print('gds write ../gds/' + project_with_id + '_fill_pattern.gds', file=ofile)
+ else:
+ print('gds write ' + project_with_id + '_fill_pattern.gds', file=ofile)
+ print('set endtime [orig_clock format [orig_clock seconds] -format "%D %T"]', file=ofile)
+ print('puts stdout "Ended: $endtime"', file=ofile)
+ print('quit -noprompt', file=ofile)
+ ofile.close()
+
+ myenv = os.environ.copy()
+ myenv['MAGTYPE'] = 'mag'
+
+ if not testmode:
+ # Diagnostic
+ # print('This script will generate file ' + project_with_id + '_fill_pattern.gds')
+ print('This script will generate files ' + project_with_id + '_fill_pattern_x_y.gds')
+ print('Now generating fill patterns. This may take. . . quite. . . a while.', flush=True)
+ mproc = subprocess.run(['magic', '-dnull', '-noconsole',
+ '-rcfile', rcfile, magpath + '/generate_fill.tcl'],
+ stdin = subprocess.DEVNULL,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.PIPE,
+ cwd = magpath,
+ env = myenv,
+ universal_newlines = True)
+ if mproc.stdout:
+ for line in mproc.stdout.splitlines():
+ print(line)
+ if mproc.stderr:
+ print('Error message output from magic:')
+ for line in mproc.stderr.splitlines():
+ print(line)
+ if mproc.returncode != 0:
+ print('ERROR: Magic exited with status ' + str(mproc.returncode))
+
+ if distmode:
+ # If using distributed mode, then run magic on each of the generated
+ # layout files
+ pool = multiprocessing.Pool()
+ magfiles = glob.glob(magpath + '/' + project_with_id + '_fill_pattern_*.mag')
+ # NOTE: Adding 'x' to the end of each filename, or else magic will
+ # try to read it from the command line as well as passing it as an
+ # argument to the script. We only want it passed as an argument.
+ magxfiles = list(item + 'x' for item in magfiles)
+ pool.map(makegds, magxfiles)
+
+ # If using distributed mode, then remove all of the temporary .mag files
+ # and then run the final generation script.
+ for file in magfiles:
+ os.remove(file)
+
+ mproc = subprocess.run(['magic', '-dnull', '-noconsole',
+ '-rcfile', rcfile, magpath + '/generate_fill_final.tcl'],
+ stdin = subprocess.DEVNULL,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.PIPE,
+ cwd = magpath,
+ env = myenv,
+ universal_newlines = True)
+ if mproc.stdout:
+ for line in mproc.stdout.splitlines():
+ print(line)
+ if mproc.stderr:
+ print('Error message output from magic:')
+ for line in mproc.stderr.splitlines():
+ print(line)
+ if mproc.returncode != 0:
+ print('ERROR: Magic exited with status ' + str(mproc.returncode))
+
+ if not keepmode:
+ # Remove fill generation script
+ os.remove(magpath + '/generate_fill.tcl')
+ # Remove all individual fill tiles, leaving only the composite GDS.
+ filelist = os.listdir(magpath)
+ for file in filelist:
+ if os.path.splitext(magpath + '/' + file)[1] == '.gds':
+ if file.startswith(project_with_id + '_fill_pattern_'):
+ os.remove(magpath + '/' + file)
+
+ if distmode:
+ os.remove(magpath + '/generate_fill_dist.tcl')
+ os.remove(magpath + '/generate_fill_final.tcl')
+ os.remove(magpath + '/fill_gen_info.txt')
+ if testmode:
+ magfiles = glob.glob(magpath + '/' + project_with_id + '_fill_pattern_*.mag')
+ for file in magfiles:
+ os.remove(file)
+
+ print('Done!')
+ exit(0)
diff --git a/caravel/scripts/generate_fill_orig.py b/caravel/scripts/generate_fill_orig.py
new file mode 100644
index 0000000..3a43a8c
--- /dev/null
+++ b/caravel/scripts/generate_fill_orig.py
@@ -0,0 +1,268 @@
+#!/usr/bin/env python3
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+#
+# generate_fill_orig.py ---
+#
+# Run the fill generation on a layout top level.
+# This is the older version that does not have a "-dist" option for
+# distributed (multiprocessing) operation.
+#
+
+import sys
+import os
+import re
+import subprocess
+
+def usage():
+ print("Usage:")
+ print("generate_fill_orig.py [<path_to_project>] [-keep] [-test]")
+ print("")
+ print("where:")
+ print(" <path_to_project> is the path to the project top level directory.")
+ print("")
+ print(" If <path_to_project> is not given, then it is assumed to be the cwd.")
+ print(" If '-keep' is specified, then keep the generation script.")
+ print(" If '-test' is specified, then create but do not run the generation script.")
+ return 0
+
+if __name__ == '__main__':
+
+ optionlist = []
+ arguments = []
+
+ debugmode = False
+ keepmode = False
+ testmode = False
+
+ for option in sys.argv[1:]:
+ if option.find('-', 0) == 0:
+ optionlist.append(option)
+ else:
+ arguments.append(option)
+
+ if len(arguments) > 1:
+ print("Wrong number of arguments given to generate_fill_orig.py.")
+ usage()
+ sys.exit(1)
+
+ if len(arguments) == 1:
+ user_project_path = arguments[0]
+ else:
+ user_project_path = os.getcwd()
+
+ if not os.path.isdir(user_project_path):
+ print('Error: Project path "' + user_project_path + '" does not exist or is not readable.')
+ sys.exit(1)
+
+ # Check for valid user ID
+ user_id_value = None
+ if os.path.isfile(user_project_path + '/info.yaml'):
+ with open(user_project_path + '/info.yaml', 'r') as ifile:
+ infolines = ifile.read().splitlines()
+ for line in infolines:
+ kvpair = line.split(':')
+ if len(kvpair) == 2:
+ key = kvpair[0].strip()
+ value = kvpair[1].strip()
+ if key == 'project_id':
+ user_id_value = value.strip('"\'')
+ break
+
+ project = 'caravel'
+ if user_id_value:
+ project_with_id = project + '_' + user_id_value
+ else:
+ print('Error: No project_id found in info.yaml file.')
+ sys.exit(1)
+
+ if '-debug' in optionlist:
+ debugmode = True
+ if '-keep' in optionlist:
+ keepmode = True
+ if '-test' in optionlist:
+ testmode = True
+
+ magpath = user_project_path + '/mag'
+ rcfile = magpath + '/.magicrc'
+
+ if not os.path.isfile(rcfile):
+ rcfile = None
+
+ topdir = user_project_path
+ gdsdir = topdir + '/gds'
+ hasgdsdir = True if os.path.isdir(gdsdir) else False
+
+ with open(magpath + '/generate_fill.tcl', 'w') as ofile:
+ print('#!/bin/env wish', file=ofile)
+ print('drc off', file=ofile)
+ print('tech unlock *', file=ofile)
+ print('snap internal', file=ofile)
+ print('box values 0 0 0 0', file=ofile)
+ print('box size 700um 700um', file=ofile)
+ print('set stepbox [box values]', file=ofile)
+ print('set stepwidth [lindex $stepbox 2]', file=ofile)
+ print('set stepheight [lindex $stepbox 3]', file=ofile)
+ print('', file=ofile)
+ print('set starttime [orig_clock format [orig_clock seconds] -format "%D %T"]', file=ofile)
+ print('puts stdout "Started: $starttime"', file=ofile)
+ print('', file=ofile)
+ # Read the user project from GDS, as there is not necessarily a magic database file
+ # to go along with this.
+ # print('gds read ../gds/user_project_wrapper', file=ofile)
+ # Now read the full caravel project
+ # print('load ' + project + ' -dereference', file=ofile)
+ print('gds readonly true', file=ofile)
+ print('gds rescale false', file=ofile)
+ print('gds read ../gds/caravel', file=ofile)
+ print('select top cell', file=ofile)
+ print('expand', file=ofile)
+ print('cif ostyle wafflefill(tiled)', file=ofile)
+ print('', file=ofile)
+ print('set fullbox [box values]', file=ofile)
+ print('set xmax [lindex $fullbox 2]', file=ofile)
+ print('set xmin [lindex $fullbox 0]', file=ofile)
+ print('set fullwidth [expr {$xmax - $xmin}]', file=ofile)
+ print('set xtiles [expr {int(ceil(($fullwidth + 0.0) / $stepwidth))}]', file=ofile)
+ print('set ymax [lindex $fullbox 3]', file=ofile)
+ print('set ymin [lindex $fullbox 1]', file=ofile)
+ print('set fullheight [expr {$ymax - $ymin}]', file=ofile)
+ print('set ytiles [expr {int(ceil(($fullheight + 0.0) / $stepheight))}]', file=ofile)
+ print('box size $stepwidth $stepheight', file=ofile)
+ print('set xbase [lindex $fullbox 0]', file=ofile)
+ print('set ybase [lindex $fullbox 1]', file=ofile)
+ print('', file=ofile)
+
+ # Break layout into tiles and process each separately
+ print('for {set y 0} {$y < $ytiles} {incr y} {', file=ofile)
+ print(' for {set x 0} {$x < $xtiles} {incr x} {', file=ofile)
+ print(' set xlo [expr $xbase + $x * $stepwidth]', file=ofile)
+ print(' set ylo [expr $ybase + $y * $stepheight]', file=ofile)
+ print(' set xhi [expr $xlo + $stepwidth]', file=ofile)
+ print(' set yhi [expr $ylo + $stepheight]', file=ofile)
+ print(' if {$xhi > $fullwidth} {set xhi $fullwidth}', file=ofile)
+ print(' if {$yhi > $fullheight} {set yhi $fullheight}', file=ofile)
+ print(' box values $xlo $ylo $xhi $yhi', file=ofile)
+ # The flattened area must be larger than the fill tile by >1.5um
+ print(' box grow c 1.6um', file=ofile)
+
+ # Flatten into a cell with a new name
+ print(' puts stdout "Flattening layout of tile x=$x y=$y. . . "', file=ofile)
+ print(' flush stdout', file=ofile)
+ print(' update idletasks', file=ofile)
+ print(' flatten -dobox -nolabels ' + project_with_id + '_fill_pattern_${x}_$y', file=ofile)
+ print(' load ' + project_with_id + '_fill_pattern_${x}_$y', file=ofile)
+
+ # Remove any GDS_FILE reference (there should not be any?)
+ print(' property GDS_FILE ""', file=ofile)
+ # Set boundary using comment layer, to the size of the step box
+ # This corresponds to the "topbox" rule in the wafflefill(tiled) style
+ print(' select top cell', file=ofile)
+ print(' erase comment', file=ofile)
+ print(' box values $xlo $ylo $xhi $yhi', file=ofile)
+ print(' paint comment', file=ofile)
+ print(' puts stdout "Writing GDS. . . "', file=ofile)
+ print(' flush stdout', file=ofile)
+ print(' update idletasks', file=ofile)
+ print(' gds write ' + project_with_id + '_fill_pattern_${x}_$y.gds', file=ofile)
+
+ # Reload project top
+ print(' load ' + project, file=ofile)
+
+ # Remove last generated cell to save memory
+ print(' cellname delete ' + project_with_id + '_fill_pattern_${x}_$y', file=ofile)
+
+ print(' }', file=ofile)
+ print('}', file=ofile)
+
+ # Now create simple "fake" views of all the tiles.
+ print('gds readonly true', file=ofile)
+ print('gds rescale false', file=ofile)
+ print('for {set y 0} {$y < $ytiles} {incr y} {', file=ofile)
+ print(' for {set x 0} {$x < $xtiles} {incr x} {', file=ofile)
+ print(' set xlo [expr $xbase + $x * $stepwidth]', file=ofile)
+ print(' set ylo [expr $ybase + $y * $stepheight]', file=ofile)
+ print(' set xhi [expr $xlo + $stepwidth]', file=ofile)
+ print(' set yhi [expr $ylo + $stepheight]', file=ofile)
+ print(' load ' + project_with_id + '_fill_pattern_${x}_$y -quiet', file=ofile)
+ print(' box values $xlo $ylo $xhi $yhi', file=ofile)
+ print(' paint comment', file=ofile)
+ print(' property FIXED_BBOX "$xlo $ylo $xhi $yhi"', file=ofile)
+ print(' property GDS_FILE ' + project_with_id + '_fill_pattern_${x}_${y}.gds', file=ofile)
+ print(' property GDS_START 0', file=ofile)
+ print(' }', file=ofile)
+ print('}', file=ofile)
+
+ # Now tile everything back together
+ print('load ' + project_with_id + '_fill_pattern -quiet', file=ofile)
+ print('for {set y 0} {$y < $ytiles} {incr y} {', file=ofile)
+ print(' for {set x 0} {$x < $xtiles} {incr x} {', file=ofile)
+ print(' box values 0 0 0 0', file=ofile)
+ print(' getcell ' + project_with_id + '_fill_pattern_${x}_$y child 0 0', file=ofile)
+ print(' }', file=ofile)
+ print('}', file=ofile)
+
+ # And write final GDS
+ print('puts stdout "Writing final GDS"', file=ofile)
+
+ print('cif *hier write disable', file=ofile)
+ print('cif *array write disable', file=ofile)
+ if hasgdsdir:
+ print('gds write ../gds/' + project_with_id + '_fill_pattern.gds', file=ofile)
+ else:
+ print('gds write ' + project_with_id + '_fill_pattern.gds', file=ofile)
+ print('set endtime [orig_clock format [orig_clock seconds] -format "%D %T"]', file=ofile)
+ print('puts stdout "Ended: $endtime"', file=ofile)
+ print('quit -noprompt', file=ofile)
+
+ myenv = os.environ.copy()
+ myenv['MAGTYPE'] = 'mag'
+
+ if not testmode:
+ # Diagnostic
+ # print('This script will generate file ' + project_with_id + '_fill_pattern.gds')
+ print('This script will generate files ' + project_with_id + '_fill_pattern_x_y.gds')
+ print('Now generating fill patterns. This may take. . . quite. . . a while.', flush=True)
+ mproc = subprocess.run(['magic', '-dnull', '-noconsole',
+ '-rcfile', rcfile, magpath + '/generate_fill.tcl'],
+ stdin = subprocess.DEVNULL,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.PIPE,
+ cwd = magpath,
+ env = myenv,
+ universal_newlines = True)
+ if mproc.stdout:
+ for line in mproc.stdout.splitlines():
+ print(line)
+ if mproc.stderr:
+ print('Error message output from magic:')
+ for line in mproc.stderr.splitlines():
+ print(line)
+ if mproc.returncode != 0:
+ print('ERROR: Magic exited with status ' + str(mproc.returncode))
+
+ if not keepmode:
+ # Remove fill generation script
+ os.remove(magpath + '/generate_fill.tcl')
+ # Remove all individual fill tiles, leaving only the composite GDS.
+ filelist = os.listdir(magpath)
+ for file in filelist:
+ if os.path.splitext(magpath + '/' + file)[1] == '.gds':
+ if file.startswith(project + '_fill_pattern_'):
+ os.remove(magpath + '/' + file)
+
+ print('Done!')
+ exit(0)
diff --git a/caravel/scripts/make_bump_bonds.tcl b/caravel/scripts/make_bump_bonds.tcl
new file mode 100644
index 0000000..ade81d6
--- /dev/null
+++ b/caravel/scripts/make_bump_bonds.tcl
@@ -0,0 +1,702 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+#----------------------------------------------------------------------
+# Assumes running magic -T micross using the micross technology file
+# from the open_pdks installation of sky130A
+#----------------------------------------------------------------------
+# bump bond pitch is 500um. Bump diameter is set by the technology
+
+namespace path {::tcl::mathop ::tcl::mathfunc}
+
+if {[catch {set PDKPATH $env(PDKPATH)}]} {
+ set PDKPATH "$::env(PDK_ROOT)/sky130A"
+}
+
+source $PDKPATH/libs.tech/magic/current/bump_bond_generator/bump_bond.tcl
+
+# Caravel dimensions, in microns
+set chipwidth 3588
+set chipheight 5188
+
+set halfwidth [/ $chipwidth 2]
+set halfheight [/ $chipheight 2]
+
+set columns 6
+set rows 10
+
+set bump_pitch 500
+
+set llx [- $halfwidth [* [- [/ $columns 2] 0.5] $bump_pitch]]
+set lly [- $halfheight [* [- [/ $rows 2] 0.5] $bump_pitch]]
+
+# Create a new cell
+load caravel_bump_bond -quiet
+
+# Build the bump cells
+make_bump_bond 0
+make_bump_bond 45
+
+# View the whole chip during generation. This is not strictly
+# necessary, but looks nice!
+snap internal
+box values 0 0 ${chipwidth}um ${chipheight}um
+paint glass
+view
+erase glass
+box values 0 0 0 0
+grid 250um 250um 45um 95um
+
+# Starting from the bottom left-hand corner and scanning across and up,
+# these are the orientations of the bump bond pad tapers:
+set tapers {}
+lappend tapers 180 225 270 270 270 270
+lappend tapers 180 135 225 270 0 0
+lappend tapers 180 135 135 270 315 0
+lappend tapers 180 135 135 315 315 0
+lappend tapers 135 135 0 180 315 0
+lappend tapers 180 135 0 180 315 0
+lappend tapers 180 135 180 315 315 0
+lappend tapers 180 180 135 45 315 0
+lappend tapers 135 135 135 45 45 45
+lappend tapers 90 90 90 90 45 90
+
+box values 0 0 0 0
+set t 0
+for {set y 0} {$y < $rows} {incr y} {
+ for {set x 0} {$x < $columns} {incr x} {
+ set xpos [+ $llx [* $x $bump_pitch]]
+ set ypos [+ $lly [* $y $bump_pitch]]
+ draw_bump_bond $xpos $ypos [lindex $tapers $t]
+ incr t
+ }
+}
+
+# The pad at E6 has wires exiting two sides, so put another pad down
+# at the other orientation.
+set y 4
+set x 4
+set xpos [+ $llx [* $x $bump_pitch]]
+set ypos [+ $lly [* $y $bump_pitch]]
+draw_bump_bond $xpos $ypos 180
+
+select top cell
+expand
+
+# These are the pad Y positions on the left side from bottom to top
+
+set leftpads {}
+lappend leftpads 377.5 588.5 950.5 1166.5 1382.5 1598.5 1814.5
+lappend leftpads 2030.5 2241.5 2452.5 2668.5 2884.5 3100.5
+lappend leftpads 3316.5 3532.5 3748.5 3964.5 4175.5 4386.5 4597.5 4813.5
+
+# These are the pad X positions on the top side from left to right
+
+set toppads {}
+lappend toppads 423.5 680.5 937.5 1194.5 1452.5 1704.5 1961.5 2406.5
+lappend toppads 2663.5 2915.5 3172.5
+
+# These are the pad Y positions on the right side from bottom to top
+
+set rightpads {}
+lappend rightpads 537.5 763.5 988.5 1214.5 1439.5 1664.5 1890.5
+lappend rightpads 2115.5 2336.5 2556.5 2776.5 3002.5 3227.5 3453.5
+lappend rightpads 3678.5 3903.5 4129.5 4349.5 4575.5 4795.5
+
+# These are the pad X positions on the bottom side from left to right
+
+set bottompads {}
+lappend bottompads 431.5 700.5 969.5 1243.5 1512.5 1786.5 2060.5
+lappend bottompads 2334.5 2608.5 2882.5 3151.5
+
+set leftpadx 64.6
+set rightpadx 3523.78
+set bottompady 64.6
+set toppady 5123.78
+
+set xpos $leftpadx
+for {set y 0} {$y < [llength $leftpads]} {incr y} {
+ set ypos [lindex $leftpads $y]
+ draw_pad_bond $xpos $ypos
+}
+
+set ypos $toppady
+for {set x 0} {$x < [llength $toppads]} {incr x} {
+ set xpos [lindex $toppads $x]
+ draw_pad_bond $xpos $ypos
+}
+
+set xpos $rightpadx
+for {set y 0} {$y < [llength $rightpads]} {incr y} {
+ set ypos [lindex $rightpads $y]
+ draw_pad_bond $xpos $ypos
+}
+
+set ypos $bottompady
+for {set x 0} {$x < [llength $bottompads]} {incr x} {
+ set xpos [lindex $bottompads $x]
+ draw_pad_bond $xpos $ypos
+}
+
+# Now route between the wirebond pads and the bump bond pads
+# routes start centered on the wirebond pad and align to grid points
+# on a 1/2 ball pitch, although positions do not need to be on
+# integer values. The overlaid grid starts 1/2 pitch to the left
+# and below the center of the bottom left bump bond. Grid columns
+# are numbered 0 to 12, and grid rows are numbered 0 to 20. To
+# convert to a micron unit coordinate, use the to_grid procedure
+# defined below.
+
+set gridllx [- $llx 250.0]
+set gridlly [- $lly 250.0]
+set gridpitchx 250.0
+set gridpitchy 250.0
+
+proc to_grid {x y} {
+ global gridllx gridlly
+ set coords []
+ catch {lappend coords [+ $gridllx [* 250.0 $x]]}
+ catch {lappend coords [+ $gridlly [* 250.0 $y]]}
+ return $coords
+}
+
+# Detailed routing, scanning left to right and from bottom to top.
+# (This really needs to be automated. . .)
+
+set wire_width 40.0
+
+# A10 vccd
+set coords [list $leftpadx [lindex $leftpads 0]]
+lappend coords {*}[to_grid -0.8 1]
+lappend coords {*}[to_grid 1 1]
+draw_pad_route $coords $wire_width
+
+# B10 resetb
+set coords [list [lindex $bottompads 1] $bottompady]
+lappend coords {*}[to_grid 1.9 0.2]
+lappend coords {*}[to_grid 2.2 0.2]
+lappend coords {*}[to_grid 3 1]
+draw_pad_route $coords $wire_width
+
+# C10 flash csb
+set coords [list [lindex $bottompads 4] $bottompady]
+lappend coords {*}[to_grid 5 0]
+lappend coords {*}[to_grid 5 1]
+draw_pad_route $coords $wire_width
+
+# D10 flash io0
+set coords [list [lindex $bottompads 6] $bottompady]
+lappend coords {*}[to_grid 7 0]
+lappend coords {*}[to_grid 7 1]
+draw_pad_route $coords $wire_width
+
+# E10 gpio
+set coords [list [lindex $bottompads 8] $bottompady]
+lappend coords {*}[to_grid 9 0.2]
+lappend coords {*}[to_grid 9 1]
+draw_pad_route $coords $wire_width
+
+# F10 vdda
+set coords [list [lindex $bottompads 10] $bottompady]
+lappend coords {*}[to_grid 11 0.3]
+lappend coords {*}[to_grid 11 1]
+draw_pad_route $coords $wire_width
+
+# A9 mprj_io[37]
+set coords [list $leftpadx [lindex $leftpads 2]]
+lappend coords {*}[to_grid -0.5 3]
+lappend coords {*}[to_grid 1 3]
+draw_pad_route $coords $wire_width
+
+# B9 mprj_io[36]
+set coords [list $leftpadx [lindex $leftpads 3]]
+lappend coords {*}[to_grid -0.6 4]
+lappend coords {*}[to_grid 2 4]
+lappend coords {*}[to_grid 3 3]
+draw_pad_route $coords $wire_width
+
+# C9 clock
+set coords [list [lindex $bottompads 2] $bottompady]
+lappend coords {*}[to_grid 3 0.2]
+lappend coords {*}[to_grid 3.4 0.2]
+lappend coords {*}[to_grid 3.8 0.6]
+lappend coords {*}[to_grid 3.8 1.6]
+lappend coords {*}[to_grid 4.5 2.3]
+lappend coords {*}[to_grid 4.5 2.5]
+lappend coords {*}[to_grid 5 3]
+draw_pad_route $coords $wire_width
+
+# D9 flash io1
+set coords [list [lindex $bottompads 7] $bottompady]
+lappend coords {*}[to_grid 8 0.1]
+lappend coords {*}[to_grid 8 1.3]
+lappend coords {*}[to_grid 7 2.3]
+lappend coords {*}[to_grid 7 3]
+draw_pad_route $coords $wire_width
+
+# E9 mprj_io[1]/SDO
+set coords [list $rightpadx [lindex $rightpads 1]]
+lappend coords {*}[to_grid 12.4 2.2]
+lappend coords {*}[to_grid 10.5 2.2]
+lappend coords {*}[to_grid 9.7 3]
+lappend coords {*}[to_grid 9 3]
+draw_pad_route $coords $wire_width
+
+# F9 mprj_io[2]/SDI
+set coords [list $rightpadx [lindex $rightpads 2]]
+lappend coords {*}[to_grid 12.3 3]
+lappend coords {*}[to_grid 11 3]
+draw_pad_route $coords $wire_width
+
+# A8 mprj_io[35]
+set coords [list $leftpadx [lindex $leftpads 4]]
+lappend coords {*}[to_grid -0.7 5]
+lappend coords {*}[to_grid 1 5]
+draw_pad_route $coords $wire_width
+
+# B8 mprj_io[34]
+set coords [list $leftpadx [lindex $leftpads 5]]
+lappend coords {*}[to_grid -0.7 5.8]
+lappend coords {*}[to_grid 2.2 5.8]
+lappend coords {*}[to_grid 3 5]
+draw_pad_route $coords $wire_width
+
+# C8 mprj_io[33]
+set coords [list $leftpadx [lindex $leftpads 6]]
+lappend coords {*}[to_grid -0.3 6.2]
+lappend coords {*}[to_grid 3.8 6.2]
+lappend coords {*}[to_grid 5 5]
+draw_pad_route $coords $wire_width
+
+# D8 flash clk
+set coords [list [lindex $bottompads 5] $bottompady]
+lappend coords {*}[to_grid 6 0]
+lappend coords {*}[to_grid 6 1]
+lappend coords {*}[to_grid 6.2 1.2]
+lappend coords {*}[to_grid 6.2 3.5]
+lappend coords {*}[to_grid 7 4.3]
+lappend coords {*}[to_grid 7 5]
+draw_pad_route $coords $wire_width
+
+# E8 mprj_io[3]/CSB
+set coords [list $rightpadx [lindex $rightpads 3]]
+lappend coords {*}[to_grid 12.4 4]
+lappend coords {*}[to_grid 10 4]
+lappend coords {*}[to_grid 9 5]
+draw_pad_route $coords $wire_width
+
+# F8 mrpj_io[4]/SCK
+set coords [list $rightpadx [lindex $rightpads 4]]
+lappend coords {*}[to_grid 12.5 5]
+lappend coords {*}[to_grid 11 5]
+draw_pad_route $coords $wire_width
+
+# A7 mrpj_io[32]
+set coords [list $leftpadx [lindex $leftpads 7]]
+lappend coords {*}[to_grid -0.2 7]
+lappend coords {*}[to_grid 1 7]
+draw_pad_route $coords $wire_width
+
+# B7 vssd2
+set coords [list $leftpadx [lindex $leftpads 8]]
+lappend coords {*}[to_grid -0.1 7.8]
+lappend coords {*}[to_grid 2.2 7.8]
+lappend coords {*}[to_grid 3 7]
+draw_pad_route $coords $wire_width
+
+# C7 vdda2
+set coords [list $leftpadx [lindex $leftpads 9]]
+lappend coords {*}[to_grid 0.3 8.2]
+lappend coords {*}[to_grid 2.3 8.2]
+lappend coords {*}[to_grid 2.5 8]
+lappend coords {*}[to_grid 4 8]
+lappend coords {*}[to_grid 5 7]
+draw_pad_route $coords $wire_width
+
+# D7 mrpj_io[0]/JTAG
+set coords [list $rightpadx [lindex $rightpads 0]]
+lappend coords {*}[to_grid 12.8 1.8]
+lappend coords {*}[to_grid 10.2 1.8]
+lappend coords {*}[to_grid 9.8 2.2]
+lappend coords {*}[to_grid 8.6 2.2]
+lappend coords {*}[to_grid 8.2 2.6]
+lappend coords {*}[to_grid 8.2 5.8]
+lappend coords {*}[to_grid 7 7]
+draw_pad_route $coords $wire_width
+
+# E7 mrpj_io[5]/ser_rx
+set coords [list $rightpadx [lindex $rightpads 5]]
+lappend coords {*}[to_grid 12.6 6]
+lappend coords {*}[to_grid 10 6]
+lappend coords {*}[to_grid 9 7]
+draw_pad_route $coords $wire_width
+
+# F7 mprj_io[6]/ser_tx
+set coords [list $rightpadx [lindex $rightpads 6]]
+lappend coords {*}[to_grid 12.7 7]
+lappend coords {*}[to_grid 11 7]
+draw_pad_route $coords $wire_width
+
+# A6 mprj_io[31]
+set coords [list $leftpadx [lindex $leftpads 10]]
+lappend coords {*}[to_grid -0.3 10.3]
+lappend coords {*}[to_grid 1 9]
+draw_pad_route $coords $wire_width
+
+# B6 mprj_io[30]
+set coords [list $leftpadx [lindex $leftpads 11]]
+lappend coords {*}[to_grid -0.5 10.8]
+lappend coords {*}[to_grid -0.3 10.8]
+lappend coords {*}[to_grid 0.5 10]
+lappend coords {*}[to_grid 2 10]
+lappend coords {*}[to_grid 3 9]
+draw_pad_route $coords $wire_width
+
+# C6 vssio/vssa/vssd: Connects to D6, D5, C5
+set coords [to_grid 5 9]
+lappend coords {*}[to_grid 5.65 9]
+lappend coords {*}[to_grid 5.85 9.2]
+lappend coords {*}[to_grid 6 9.2]
+draw_pad_route $coords $wire_width
+
+# D6 vssio/vssa/vssd
+set coords [to_grid 7 9]
+lappend coords {*}[to_grid 6.35 9]
+lappend coords {*}[to_grid 6.15 8.8]
+lappend coords {*}[to_grid 6 8.8]
+draw_pad_route $coords $wire_width
+
+# D6 vssio/vssa/vssd also goes to:
+set coords [list [lindex $bottompads 0] $bottompady]
+lappend coords {*}[to_grid 0.9 0.2]
+lappend coords {*}[to_grid 1.3 0.2]
+lappend coords {*}[to_grid 2 0.9]
+lappend coords {*}[to_grid 2 1.5]
+lappend coords {*}[to_grid 2.3 1.8]
+lappend coords {*}[to_grid 3.5 1.8]
+lappend coords {*}[to_grid 4.2 2.5]
+lappend coords {*}[to_grid 4.2 3.5]
+lappend coords {*}[to_grid 4.5 3.8]
+lappend coords {*}[to_grid 5.3 3.8]
+lappend coords {*}[to_grid 5.8 3.3]
+lappend coords {*}[to_grid 5.8 2.5]
+lappend coords {*}[to_grid 5.3 2]
+lappend coords {*}[to_grid 4.8 2]
+lappend coords {*}[to_grid 4.2 1.4]
+lappend coords {*}[to_grid 4.2 0.3]
+lappend coords {*}[list [lindex $bottompads 3] $bottompady]
+draw_pad_route $coords $wire_width
+
+# D6 vssio/vssa/vssd also goes to:
+set coords [list [lindex $bottompads 9] $bottompady]
+lappend coords {*}[to_grid 10 0.3]
+lappend coords {*}[to_grid 10 1.4]
+lappend coords {*}[to_grid 9.6 1.8]
+lappend coords {*}[to_grid 8.5 1.8]
+lappend coords {*}[to_grid 7.8 2.5]
+lappend coords {*}[to_grid 7.8 5.5]
+lappend coords {*}[to_grid 7.3 6]
+lappend coords {*}[to_grid 6.2 6]
+draw_pad_route $coords $wire_width
+
+# D6 vssio/vssa/vssd also goes to:
+set coords [list [lindex $toppads 5] $toppady]
+lappend coords {*}[to_grid 6 19.7]
+lappend coords {*}[to_grid 6 16]
+lappend coords {*}[to_grid 5.8 15.8]
+lappend coords {*}[to_grid 5.8 12.2]
+lappend coords {*}[to_grid 6 12]
+lappend coords {*}[to_grid 6 8]
+lappend coords {*}[to_grid 6.2 7.8]
+lappend coords {*}[to_grid 6.2 4.3]
+lappend coords {*}[to_grid 5.5 3.6]
+draw_pad_route $coords $wire_width
+
+# E6 vssa1
+set coords [list $rightpadx [lindex $rightpads 7]]
+lappend coords {*}[to_grid 12.8 8]
+lappend coords {*}[to_grid 10 8]
+lappend coords {*}[to_grid 9 9]
+draw_pad_route $coords $wire_width
+
+# E6 vssa1 also goes to
+set coords [list [lindex $toppads 9] $toppady]
+lappend coords {*}[to_grid 10 19.5]
+lappend coords {*}[to_grid 10 18.5]
+lappend coords {*}[to_grid 9.5 18]
+lappend coords {*}[to_grid 8.5 18]
+lappend coords {*}[to_grid 8 17.5]
+lappend coords {*}[to_grid 8 16.5]
+lappend coords {*}[to_grid 7.5 16]
+lappend coords {*}[to_grid 6.7 16]
+lappend coords {*}[to_grid 6.2 15.5]
+lappend coords {*}[to_grid 6.2 12.6]
+lappend coords {*}[to_grid 6.7 12]
+lappend coords {*}[to_grid 7.3 12]
+lappend coords {*}[to_grid 7.8 11.5]
+lappend coords {*}[to_grid 7.8 10.2]
+lappend coords {*}[to_grid 8 10]
+lappend coords {*}[to_grid 8 9.3]
+lappend coords {*}[to_grid 8.3 9]
+lappend coords {*}[to_grid 9 9]
+draw_pad_route $coords $wire_width
+
+# F6 vssd1
+set coords [list $rightpadx [lindex $rightpads 8]]
+lappend coords {*}[to_grid 12.9 9]
+lappend coords {*}[to_grid 11 9]
+draw_pad_route $coords $wire_width
+
+# A5 mprj_io[29]
+set coords [list $leftpadx [lindex $leftpads 12]]
+lappend coords {*}[to_grid 0.2 11]
+lappend coords {*}[to_grid 1 11]
+draw_pad_route $coords $wire_width
+
+# B5 mprj_io[28]
+set coords [list $leftpadx [lindex $leftpads 13]]
+lappend coords {*}[to_grid 0 12]
+lappend coords {*}[to_grid 2 12]
+lappend coords {*}[to_grid 3 11]
+draw_pad_route $coords $wire_width
+
+# C5 vssio/vssa/vssd : Connects to D6, C6, D5
+set coords [to_grid 5 11]
+lappend coords {*}[to_grid 5.65 11]
+lappend coords {*}[to_grid 5.85 11.2]
+lappend coords {*}[to_grid 6 11.2]
+draw_pad_route $coords $wire_width
+
+# D5 vssio/vssa/vssd : Connects to D6, C6, C5
+set coords [to_grid 7 11]
+lappend coords {*}[to_grid 6.35 11]
+lappend coords {*}[to_grid 6.15 10.8]
+lappend coords {*}[to_grid 6 10.8]
+draw_pad_route $coords $wire_width
+
+# E5 mprj_io[7]/irq
+set coords [list $rightpadx [lindex $rightpads 10]]
+lappend coords {*}[to_grid 12.4 10.2]
+lappend coords {*}[to_grid 9.8 10.2]
+lappend coords {*}[to_grid 9 11]
+draw_pad_route $coords $wire_width
+
+# F5 mprj_io[8]/flash2 csb
+set coords [list $rightpadx [lindex $rightpads 11]]
+lappend coords {*}[to_grid 12.3 11]
+lappend coords {*}[to_grid 11 11]
+draw_pad_route $coords $wire_width
+
+# A4 mprj_io[27]
+set coords [list $leftpadx [lindex $leftpads 14]]
+lappend coords {*}[to_grid -0.1 13]
+lappend coords {*}[to_grid 1 13]
+draw_pad_route $coords $wire_width
+
+# B4 mprj_io[26]
+set coords [list $leftpadx [lindex $leftpads 15]]
+lappend coords {*}[to_grid -0.2 14]
+lappend coords {*}[to_grid 2 14]
+lappend coords {*}[to_grid 3 13]
+draw_pad_route $coords $wire_width
+
+# C4 vddio
+set coords [list $leftpadx [lindex $leftpads 1]]
+lappend coords {*}[to_grid -0.8 2]
+lappend coords {*}[to_grid 1.8 2]
+lappend coords {*}[to_grid 2 2.2]
+lappend coords {*}[to_grid 3.3 2.2]
+lappend coords {*}[to_grid 3.8 2.7]
+lappend coords {*}[to_grid 3.8 3.7]
+lappend coords {*}[to_grid 4.3 4.2]
+lappend coords {*}[to_grid 5.3 4.2]
+lappend coords {*}[to_grid 5.8 4.7]
+lappend coords {*}[to_grid 5.8 7.4]
+lappend coords {*}[to_grid 5.2 8]
+lappend coords {*}[to_grid 4.7 8]
+lappend coords {*}[to_grid 4 8.7]
+lappend coords {*}[to_grid 4 13]
+draw_pad_route $coords $wire_width
+
+# C4 vddio is also:
+set coords [list $leftpadx [lindex $leftpads 18]]
+lappend coords {*}[to_grid 0.1 16.2]
+lappend coords {*}[to_grid 1.6 16.2]
+lappend coords {*}[to_grid 2 15.8]
+lappend coords {*}[to_grid 3.4 15.8]
+lappend coords {*}[to_grid 4 15.2]
+lappend coords {*}[to_grid 4 13]
+lappend coords {*}[to_grid 5 13]
+draw_pad_route $coords $wire_width
+
+# D4 vdda1
+set coords [list $rightpadx [lindex $rightpads 9]]
+lappend coords {*}[to_grid 12.8 9.8]
+lappend coords {*}[to_grid 9.7 9.8]
+lappend coords {*}[to_grid 9.5 10]
+lappend coords {*}[to_grid 8.8 10]
+lappend coords {*}[to_grid 8.2 10.6]
+lappend coords {*}[to_grid 8.2 11.8]
+lappend coords {*}[to_grid 7 13]
+draw_pad_route $coords $wire_width
+
+# D4 vdda1 is also:
+set coords [list $rightpadx [lindex $rightpads 16]]
+lappend coords {*}[to_grid 12.6 15.8]
+lappend coords {*}[to_grid 8.4 15.8]
+lappend coords {*}[to_grid 8 15.4]
+lappend coords {*}[to_grid 8 12.4]
+lappend coords {*}[to_grid 7.8 12.2]
+draw_pad_route $coords $wire_width
+
+# E4 mprj_io[9]/flash2 sck
+set coords [list $rightpadx [lindex $rightpads 12]]
+lappend coords {*}[to_grid 12.4 12]
+lappend coords {*}[to_grid 10 12]
+lappend coords {*}[to_grid 9 13]
+draw_pad_route $coords $wire_width
+
+# F4 mprj_io[10]/flash2 io0
+set coords [list $rightpadx [lindex $rightpads 13]]
+lappend coords {*}[to_grid 12.5 13]
+lappend coords {*}[to_grid 11 13]
+draw_pad_route $coords $wire_width
+
+# A3 mprj_io[25]
+set coords [list $leftpadx [lindex $leftpads 16]]
+lappend coords {*}[to_grid -0.4 15]
+lappend coords {*}[to_grid 1 15]
+draw_pad_route $coords $wire_width
+
+# B3 vssa2
+set coords [list $leftpadx [lindex $leftpads 17]]
+lappend coords {*}[to_grid -0.4 15.8]
+lappend coords {*}[to_grid 0 15.8]
+lappend coords {*}[to_grid 1.3 15.8]
+lappend coords {*}[to_grid 2.2 15]
+lappend coords {*}[to_grid 3 15]
+draw_pad_route $coords $wire_width
+
+# C3 mprj_io[24]
+set coords [list $leftpadx [lindex $leftpads 20]]
+lappend coords {*}[to_grid 0 18]
+lappend coords {*}[to_grid 1.5 18]
+lappend coords {*}[to_grid 2 17.5]
+lappend coords {*}[to_grid 2 16.5]
+lappend coords {*}[to_grid 2.3 16.2]
+lappend coords {*}[to_grid 3.8 16.2]
+lappend coords {*}[to_grid 5 15]
+draw_pad_route $coords $wire_width
+
+# D3 mprj_io[13]
+set coords [list $rightpadx [lindex $rightpads 17]]
+lappend coords {*}[to_grid 12 16.2]
+lappend coords {*}[to_grid 8.2 16.2]
+lappend coords {*}[to_grid 7 15]
+draw_pad_route $coords $wire_width
+
+# E3 mprj_io[11]/flash2 io1
+set coords [list $rightpadx [lindex $rightpads 14]]
+lappend coords {*}[to_grid 12.6 14]
+lappend coords {*}[to_grid 10 14]
+lappend coords {*}[to_grid 9 15]
+draw_pad_route $coords $wire_width
+
+# F3 mprj_io[12]
+set coords [list $rightpadx [lindex $rightpads 15]]
+lappend coords {*}[to_grid 12.7 15]
+lappend coords {*}[to_grid 11 15]
+draw_pad_route $coords $wire_width
+
+# A2 vccd2
+set coords [list $leftpadx [lindex $leftpads 19]]
+lappend coords {*}[to_grid -0.4 17.5]
+lappend coords {*}[to_grid 0.5 17.5]
+lappend coords {*}[to_grid 1 17]
+draw_pad_route $coords $wire_width
+
+# B2 mprj_io[22]
+set coords [list [lindex $toppads 1] $toppady]
+lappend coords {*}[to_grid 2 19.7]
+lappend coords {*}[to_grid 2 18]
+lappend coords {*}[to_grid 3 17]
+draw_pad_route $coords $wire_width
+
+# C2 mprj_io[20]
+set coords [list [lindex $toppads 3] $toppady]
+lappend coords {*}[to_grid 4 19.7]
+lappend coords {*}[to_grid 4 18]
+lappend coords {*}[to_grid 5 17]
+draw_pad_route $coords $wire_width
+
+# D2 mprj_io[17]
+set coords [list [lindex $toppads 7] $toppady]
+lappend coords {*}[to_grid 8 19.7]
+lappend coords {*}[to_grid 8 18]
+lappend coords {*}[to_grid 7 17]
+draw_pad_route $coords $wire_width
+
+# E2 mprj_io[14]
+set coords [list $rightpadx [lindex $rightpads 19]]
+lappend coords {*}[to_grid 12.6 18.5]
+lappend coords {*}[to_grid 12 18.5]
+lappend coords {*}[to_grid 11.5 18]
+lappend coords {*}[to_grid 10 18]
+lappend coords {*}[to_grid 9 17]
+draw_pad_route $coords $wire_width
+
+# F2 vccd1
+set coords [list $rightpadx [lindex $rightpads 18]]
+lappend coords {*}[to_grid 12.5 17.5]
+lappend coords {*}[to_grid 11.5 17.5]
+lappend coords {*}[to_grid 11 17]
+draw_pad_route $coords $wire_width
+
+# A1 mprj_io[23]
+set coords [list [lindex $toppads 0] $toppady]
+lappend coords {*}[to_grid 1 19.7]
+lappend coords {*}[to_grid 1 19]
+draw_pad_route $coords $wire_width
+
+# B1 mprj_io[21]
+set coords [list [lindex $toppads 2] $toppady]
+lappend coords {*}[to_grid 3 19.7]
+lappend coords {*}[to_grid 3 19]
+draw_pad_route $coords $wire_width
+
+# C1 mprj_io[19]
+set coords [list [lindex $toppads 4] $toppady]
+lappend coords {*}[to_grid 5 19.7]
+lappend coords {*}[to_grid 5 19]
+draw_pad_route $coords $wire_width
+
+# D1 mrpj_io[18]
+set coords [list [lindex $toppads 6] $toppady]
+lappend coords {*}[to_grid 7 19.7]
+lappend coords {*}[to_grid 7 19]
+draw_pad_route $coords $wire_width
+
+# E1 mprj_io[16]
+set coords [list [lindex $toppads 8] $toppady]
+lappend coords {*}[to_grid 9.5 20]
+lappend coords {*}[to_grid 9.5 19.5]
+lappend coords {*}[to_grid 9 19]
+draw_pad_route $coords $wire_width
+
+# F1 mprj_io[15]
+set coords [list [lindex $toppads 10] $toppady]
+lappend coords {*}[to_grid 11 19.7]
+lappend coords {*}[to_grid 11 19]
+draw_pad_route $coords $wire_width
+
diff --git a/caravel/scripts/set_user_id.py b/caravel/scripts/set_user_id.py
new file mode 100644
index 0000000..6596bd0
--- /dev/null
+++ b/caravel/scripts/set_user_id.py
@@ -0,0 +1,348 @@
+#!/usr/bin/env python3
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+#----------------------------------------------------------------------
+#
+# set_user_id.py ---
+#
+# Manipulate the magic database, GDS, and verilog source files for the
+# user_id_programming block to set the user ID number.
+#
+# The user ID number is a 32-bit value that is passed to this routine
+# as an 8-digit hex number. If not given as an option, then the script
+# will look for the value of the key "project_id" in the info.yaml file
+# in the project top level directory
+#
+# user_id_programming layout map:
+# Positions marked (in microns) for value = 0. For value = 1, move
+# the via 0.92um to the left.
+#
+# Layout grid is 0.46um x 0.34um with half-pitch offset (0.23um, 0.17um)
+#
+# Signal Via position (um)
+# name X Y
+#--------------------------------
+# mask_rev[0] 14.49 9.35
+# mask_rev[1] 16.33 9.35
+# mask_rev[2] 10.35 20.23
+# mask_rev[3] 8.05 9.35
+# mask_rev[4] 28.29 9.35
+# mask_rev[5] 21.85 25.67
+# mask_rev[6] 8.05 20.23
+# mask_rev[7] 20.47 9.35
+# mask_rev[8] 17.25 17.85
+# mask_rev[9] 25.53 12.07
+# mask_rev[10] 22.31 20.23
+# mask_rev[11] 13.11 9.35
+# mask_rev[12] 23.69 23.29
+# mask_rev[13] 24.15 12.07
+# mask_rev[14] 13.57 17.85
+# mask_rev[15] 23.23 6.97
+# mask_rev[16] 24.15 17.85
+# mask_rev[17] 8.51 17.85
+# mask_rev[18] 23.69 20.23
+# mask_rev[19] 10.81 23.29
+# mask_rev[20] 14.95 6.97
+# mask_rev[21] 18.17 23.29
+# mask_rev[22] 21.39 17.85
+# mask_rev[23] 26.45 25.67
+# mask_rev[24] 9.89 17.85
+# mask_rev[25] 15.87 17.85
+# mask_rev[26] 26.45 17.85
+# mask_rev[27] 8.51 6.97
+# mask_rev[28] 10.81 9.35
+# mask_rev[29] 27.83 20.23
+# mask_rev[30] 16.33 23.29
+# mask_rev[31] 8.05 14.79
+#----------------------------------------------------------------------
+
+import os
+import sys
+import re
+
+def usage():
+ print("Usage:")
+ print("set_user_id.py [<user_id_value>] [<path_to_project>]")
+ print("")
+ print("where:")
+ print(" <user_id_value> is a character string of eight hex digits, and")
+ print(" <path_to_project> is the path to the project top level directory.")
+ print("")
+ print(" If <user_id_value> is not given, then it must exist in the info.yaml file.")
+ print(" If <path_to_project> is not given, then it is assumed to be the cwd.")
+ return 0
+
+if __name__ == '__main__':
+
+ # Coordinate pairs in microns for the zero position on each bit
+ mask_rev = (
+ (14.49, 9.35), (16.33, 9.35), (10.35, 20.23), ( 8.05, 9.35),
+ (28.29, 9.35), (21.85, 25.67), ( 8.05, 20.23), (20.47, 9.35),
+ (17.25, 17.85), (25.53, 12.07), (22.31, 20.23), (13.11, 9.35),
+ (23.69, 23.29), (24.15, 12.07), (13.57, 17.85), (23.23, 6.97),
+ (24.15, 17.85), ( 8.51, 17.85), (23.69, 20.23), (10.81, 23.29),
+ (14.95, 6.97), (18.17, 23.29), (21.39, 17.85), (26.45, 25.67),
+ ( 9.89, 17.85), (15.87, 17.85), (26.45, 17.85), ( 8.51, 6.97),
+ (10.81, 9.35), (27.83, 20.23), (16.33, 23.29), ( 8.05, 14.79));
+
+ optionlist = []
+ arguments = []
+
+ debugmode = False
+ reportmode = False
+
+ for option in sys.argv[1:]:
+ if option.find('-', 0) == 0:
+ optionlist.append(option)
+ else:
+ arguments.append(option)
+
+ if len(arguments) > 2:
+ print("Wrong number of arguments given to set_user_id.py.")
+ usage()
+ sys.exit(0)
+
+ if '-debug' in optionlist:
+ debugmode = True
+ if '-report' in optionlist:
+ reportmode = True
+
+ user_id_value = None
+ user_project_path = None
+
+ if len(arguments) > 0:
+ user_id_value = arguments[0]
+
+ # Convert to binary
+ try:
+ user_id_int = int('0x' + user_id_value, 0)
+ user_id_bits = '{0:032b}'.format(user_id_int)
+ except:
+ user_project_path = arguments[0]
+
+ if len(arguments) == 0:
+ user_project_path = os.getcwd()
+ elif len(arguments) == 2:
+ user_project_path = arguments[1]
+ elif user_project_path == None:
+ user_project_path = arguments[0]
+ else:
+ user_project_path = os.getcwd()
+
+ if not os.path.isdir(user_project_path):
+ print('Error: Project path "' + user_project_path + '" does not exist or is not readable.')
+ sys.exit(1)
+
+ # Check for valid directories
+
+ if not user_id_value:
+ if os.path.isfile(user_project_path + '/info.yaml'):
+ with open(user_project_path + '/info.yaml', 'r') as ifile:
+ infolines = ifile.read().splitlines()
+ for line in infolines:
+ kvpair = line.split(':')
+ if len(kvpair) == 2:
+ key = kvpair[0].strip()
+ value = kvpair[1].strip()
+ if key == 'project_id':
+ user_id_value = value.strip('"\'')
+ break
+
+ if not user_id_value:
+ print('Error: No project_id key:value pair found in project info.yaml.')
+ sys.exit(1)
+
+ try:
+ user_id_int = int('0x' + user_id_value, 0)
+ user_id_bits = '{0:032b}'.format(user_id_int)
+ except:
+ print('Error: Cannot parse user ID "' + user_id_value + '" as an 8-digit hex number.')
+ sys.exit(1)
+
+ else:
+ print('Error: No info.yaml file and no user ID argument given.')
+ sys.exit(1)
+
+ if reportmode:
+ print(str(user_id_int))
+ sys.exit(0)
+
+ print('Setting project user ID to: ' + user_id_value)
+
+ magpath = user_project_path + '/mag'
+ gdspath = user_project_path + '/gds'
+ vpath = user_project_path + '/verilog'
+ errors = 0
+
+ if not os.path.isdir(gdspath):
+ print('No directory ' + gdspath + ' found (path to GDS).')
+ sys.exit(1)
+
+ if not os.path.isdir(vpath):
+ print('No directory ' + vpath + ' found (path to verilog).')
+ sys.exit(1)
+
+ if not os.path.isdir(magpath):
+ print('No directory ' + magpath + ' found (path to magic databases).')
+ sys.exit(1)
+
+ print('Step 1: Modify GDS of the user_id_programming subcell')
+
+ # Bytes leading up to via position are:
+ viarec = "00 06 0d 02 00 43 00 06 0e 02 00 2c 00 2c 10 03 "
+ viabytes = bytes.fromhex(viarec)
+
+ # Read the GDS file. If a backup was made of the zero-value
+ # program, then use it.
+
+ gdsbak = gdspath + '/user_id_prog_zero.gds'
+ gdsfile = gdspath + '/user_id_programming.gds'
+
+ if os.path.isfile(gdsbak):
+ with open(gdsbak, 'rb') as ifile:
+ gdsdata = ifile.read()
+ else:
+ with open(gdsfile, 'rb') as ifile:
+ gdsdata = ifile.read()
+
+ for i in range(0,32):
+ # Ignore any zero bits.
+ if user_id_bits[i] == '0':
+ continue
+
+ coords = mask_rev[i]
+ xum = coords[0]
+ yum = coords[1]
+
+ # Contact is 0.17 x 0.17, so add and subtract 0.085 to get
+ # the corner positions.
+
+ xllum = xum - 0.085
+ yllum = yum - 0.085
+ xurum = xum + 0.085
+ yurum = yum + 0.085
+
+ # Get the 4-byte hex values for the corner coordinates
+ xllnm = round(xllum * 1000)
+ yllnm = round(yllum * 1000)
+ xllhex = '{0:08x}'.format(xllnm)
+ yllhex = '{0:08x}'.format(yllnm)
+ xurnm = round(xurum * 1000)
+ yurnm = round(yurum * 1000)
+ xurhex = '{0:08x}'.format(xurnm)
+ yurhex = '{0:08x}'.format(yurnm)
+
+ # Magic's GDS output for vias always starts at the lower left
+ # corner and goes counterclockwise, repeating the first point.
+ viaoldposdata = viarec + xllhex + yllhex + xurhex + yllhex
+ viaoldposdata += xurhex + yurhex + xllhex + yurhex + xllhex + yllhex
+
+ # For "one" bits, the X position is moved 0.92 microns to the left
+ newxllum = xllum - 0.92
+ newxurum = xurum - 0.92
+
+ # Get the 4-byte hex values for the new corner coordinates
+ newxllnm = round(newxllum * 1000)
+ newxllhex = '{0:08x}'.format(newxllnm)
+ newxurnm = round(newxurum * 1000)
+ newxurhex = '{0:08x}'.format(newxurnm)
+
+ vianewposdata = viarec + newxllhex + yllhex + newxurhex + yllhex
+ vianewposdata += newxurhex + yurhex + newxllhex + yurhex + newxllhex + yllhex
+
+ # Diagnostic
+ if debugmode:
+ print('Bit ' + str(i) + ':')
+ print('Via position ({0:3.2f}, {1:3.2f}) to ({2:3.2f}, {3:3.2f})'.format(xllum, yllum, xurum, yurum))
+ print('Old hex string = ' + viaoldposdata)
+ print('New hex string = ' + vianewposdata)
+
+ # Convert hex strings to byte arrays
+ viaoldbytedata = bytearray.fromhex(viaoldposdata)
+ vianewbytedata = bytearray.fromhex(vianewposdata)
+
+ # Replace the old data with the new
+ if viaoldbytedata not in gdsdata:
+ print('Error: via not found for bit position ' + str(i))
+ errors += 1
+ else:
+ gdsdata = gdsdata.replace(viaoldbytedata, vianewbytedata)
+
+ if errors == 0:
+ # Keep a copy of the original
+ if not os.path.isfile(gdsbak):
+ os.rename(gdsfile, gdsbak)
+
+ with open(gdsfile, 'wb') as ofile:
+ ofile.write(gdsdata)
+
+ print('Done!')
+
+ else:
+ print('There were errors in processing. No file written.')
+ print('Ending process.')
+ sys.exit(1)
+
+ print('Step 2: Add user project ID parameter to verilog.')
+
+ changed = False
+ with open(vpath + '/rtl/caravel.v', 'r') as ifile:
+ vlines = ifile.read().splitlines()
+ outlines = []
+ for line in vlines:
+ oline = re.sub("parameter USER_PROJECT_ID = 32'h[0-9A-F]+;",
+ "parameter USER_PROJECT_ID = 32'h" + user_id_value + ";",
+ line)
+ if oline != line:
+ changed = True
+ outlines.append(oline)
+
+ if changed:
+ with open(vpath + '/rtl/caravel.v', 'w') as ofile:
+ for line in outlines:
+ print(line, file=ofile)
+ print('Done!')
+ else:
+ print('Error: No substitutions done on verilog/rtl/caravel.v.')
+ print('Ending process.')
+ sys.exit(1)
+
+ print('Step 3: Add user project ID text to top level layout.')
+
+ with open(magpath + '/user_id_textblock.mag', 'r') as ifile:
+ maglines = ifile.read().splitlines()
+ outlines = []
+ digit = 0
+ for line in maglines:
+ if 'alphaX_' in line:
+ dchar = user_id_value[digit].upper()
+ oline = re.sub('alpha_[0-9A-F]', 'alpha_' + dchar, line)
+ outlines.append(oline)
+ digit += 1
+ else:
+ outlines.append(line)
+
+ if digit == 8:
+ with open(magpath + '/user_id_textblock.mag', 'w') as ofile:
+ for line in outlines:
+ print(line, file=ofile)
+ print('Done!')
+ elif digit == 0:
+ print('Error: No digits were replaced in the layout.')
+ else:
+ print('Error: Only ' + str(digit) + ' digits were replaced in the layout.')
+
+ sys.exit(0)
diff --git a/caravel/spi/lvs/run_lvs.sh b/caravel/spi/lvs/run_lvs.sh
new file mode 100644
index 0000000..25c27a1
--- /dev/null
+++ b/caravel/spi/lvs/run_lvs.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+
+NETGEN_SETUP=$PDK_ROOT/sky130A/libs.tech/netgen/sky130A_setup.tcl
+
+netgen -batch lvs "$1 $3" "$2 $3" ${NETGEN_SETUP} $2_comp.out -json | tee $2_comp_lvs.log
diff --git a/caravel/utils/MAGIC.txt b/caravel/utils/MAGIC.txt
new file mode 100644
index 0000000..78b4d56
--- /dev/null
+++ b/caravel/utils/MAGIC.txt
@@ -0,0 +1,31 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+
+####
+
+1) You must set the PDK_ROOT variable
+
+export PDK_ROOT=~/foss/pdks/open_pdks/sky130;
+export PDKPATH=$PDK_ROOT/sky130A ;
+
+2) Useful misc utils
+
+
+
+load caravel -dereference
+drc style drc(full)
+drc why
+drc find 10 ; findbox zoom
diff --git a/caravel/utils/README.txt b/caravel/utils/README.txt
new file mode 100644
index 0000000..78b4d56
--- /dev/null
+++ b/caravel/utils/README.txt
@@ -0,0 +1,31 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+
+####
+
+1) You must set the PDK_ROOT variable
+
+export PDK_ROOT=~/foss/pdks/open_pdks/sky130;
+export PDKPATH=$PDK_ROOT/sky130A ;
+
+2) Useful misc utils
+
+
+
+load caravel -dereference
+drc style drc(full)
+drc why
+drc find 10 ; findbox zoom
diff --git a/caravel/utils/addmpwseal.tcl b/caravel/utils/addmpwseal.tcl
new file mode 100644
index 0000000..b562f93
--- /dev/null
+++ b/caravel/utils/addmpwseal.tcl
@@ -0,0 +1,25 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+drc off
+gds readonly true
+gds rescale false
+gds read ../gds/sram_1rw1r_32_256_8_sky130_lp1.gds
+load ./caravel.mag
+select top cell
+move origin -7.165um -7.120um
+box position 0 0
+getcell advSeal_6um_gen
+gds write caravel.mpw.gds
diff --git a/caravel/utils/apply_caravel.sh b/caravel/utils/apply_caravel.sh
new file mode 100644
index 0000000..1a922cf
--- /dev/null
+++ b/caravel/utils/apply_caravel.sh
@@ -0,0 +1,44 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+# To use: sh apply_caravel.sh <target_project_path> <template_caravel_path>
+
+target_project=$1
+original_caravel=$2
+
+find $original_caravel/def/* -type f ! -name "user_project_wrapper.def" ! -name "user_proj_example.def" -exec cp {} $target_project/def \;
+find $original_caravel/lef/* -type f ! -name "user_project_wrapper.lef" ! -name "user_proj_example.lef" -exec cp {} $target_project/lef \;
+find $original_caravel/gds/* -type f ! -name "user_project_wrapper.gds.gz" ! -name "user_proj_example.gds.gz" ! -name "user_project_wrapper.gds" ! -name "user_proj_example.gds" -exec cp {} $target_project/gds \;
+find $original_caravel/mag/* -type f ! -name "user_project_wrapper.mag" ! -name "user_proj_example.mag" -exec cp {} $target_project/mag \;
+cp $original_caravel/mag/.magicrc $target_project/mag/
+mkdir -p $target_project/mag/hexdigits/
+mv $target_project/mag/alpha_*.mag $target_project/mag/hexdigits/
+cp $original_caravel/maglef/* $target_project/maglef
+cp -r $original_caravel/ngspice/digital_pll $target_project/ngspice/digital_pll
+cp -r $original_caravel/ngspice/simple_por $target_project/ngspice/simple_por
+cp -r $original_caravel/scripts $target_project/scripts
+find $original_caravel/spi/lvs/* -type f ! -name "user_project_wrapper.spice" ! -name "user_proj_example.spice" -exec cp {} $target_project/spi/lvs/ \;
+cp -r $original_caravel/utils $target_project/utils
+find $original_caravel/verilog/rtl/* -type f ! -name "user_project_wrapper.v" ! -name "user_proj_example.v" -exec cp {} $target_project/verilog/rtl/ \;
+find $original_caravel/verilog/gl/* -type f ! -name "user_project_wrapper.v" ! -name "user_proj_example.v" -exec cp {} $target_project/verilog/gl/ \;
+cp $original_caravel/verilog/stubs/*.v $target_project/verilog/stubs/
+cp -r $original_caravel/verilog/dv/caravel $target_project/verilog/dv/caravel
+cp -r $original_caravel/verilog/dv/wb_utests $target_project/verilog/dv/wb_utests
+cp $original_caravel/verilog/dv/dummy_slave.v $target_project/verilog/dv/dummy_slave.v
+
+echo "You'll have to manually copy the openlane/user_project_wrapper configs based on your preference."
+echo "You'll have to manually copy the openlane/Makefile based on your preference."
+echo "You'll have to manually copy the Makefile based on your preference."
\ No newline at end of file
diff --git a/caravel/utils/core_scripts/README.md b/caravel/utils/core_scripts/README.md
new file mode 100644
index 0000000..b14c1db
--- /dev/null
+++ b/caravel/utils/core_scripts/README.md
@@ -0,0 +1,20 @@
+<!---
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+-->
+# What is this?
+
+Core scripts are doing the actual work, scripts under ../scripts are the ones that should be used.
\ No newline at end of file
diff --git a/caravel/utils/core_scripts/magic-drc.sh b/caravel/utils/core_scripts/magic-drc.sh
new file mode 100644
index 0000000..5f5068d
--- /dev/null
+++ b/caravel/utils/core_scripts/magic-drc.sh
@@ -0,0 +1,54 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+# To call: ./magic-drc.sh <target_path> <design_name> <pdk-root> <target-type> <pdk-name> <output_path>
+
+export TARGET_DIR=$1
+export DESIGN_NAME=$2
+export PDK_ROOT=$3
+export TARGET_TYPE=$4
+export PDK=$5
+export OUT_DIR=$6
+export TCL_CALL_PATH=${7:-$(pwd)}
+
+echo "Running Magic..."
+export MAGIC_MAGICRC=$PDK_ROOT/$PDK/libs.tech/magic/sky130A.magicrc
+
+magic \
+ -noconsole \
+ -dnull \
+ -rcfile $MAGIC_MAGICRC \
+ $TCL_CALL_PATH/magic-drc.tcl \
+ </dev/null \
+ |& tee $OUT_DIR/magic_drc.log
+
+TEST=$OUT_DIR/$DESIGN_NAME.magic.drc
+
+crashSignal=$(find $TEST)
+if ! [[ $crashSignal ]]; then echo "DRC Check FAILED"; exit -1; fi
+
+
+Test_Magic_violations=$(grep "COUNT: " $TEST -s | tail -1 | sed -r 's/[^0-9]*//g')
+if ! [[ $Test_Magic_violations ]]; then Test_Magic_violations=-1; fi
+if [ $Test_Magic_violations -ne -1 ]; then Test_Magic_violations=$(((Test_Magic_violations+3)/4)); fi
+
+echo "Test # of DRC Violations:"
+echo $Test_Magic_violations
+
+if [ 0 -ne $Test_Magic_violations ]; then echo "DRC Check FAILED"; exit -1; fi
+
+echo "DRC Check Passed"
+exit 0
diff --git a/caravel/utils/core_scripts/magic-drc.tcl b/caravel/utils/core_scripts/magic-drc.tcl
new file mode 100644
index 0000000..6768d3c
--- /dev/null
+++ b/caravel/utils/core_scripts/magic-drc.tcl
@@ -0,0 +1,74 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+if { $::env(TARGET_TYPE) == "gds"} {
+ gds read $::env(TARGET_DIR)/$::env(DESIGN_NAME).gds
+} else {
+ if { $::env(TARGET_TYPE) == "mag" } {
+ load $::env(TARGET_DIR)/$::env(DESIGN_NAME).mag
+ } else {
+ def read $::env(TARGET_DIR)/$::env(DESIGN_NAME).def
+ }
+}
+
+set fout [open $::env(OUT_DIR)/$::env(DESIGN_NAME).magic.drc w]
+set oscale [cif scale out]
+set cell_name $::env(DESIGN_NAME)
+magic::suspendall
+puts stdout "\[INFO\]: Loading $cell_name\n"
+flush stdout
+load $cell_name
+select top cell
+drc euclidean on
+drc style drc(full)
+drc check
+set drcresult [drc listall why]
+
+
+set count 0
+puts $fout "$cell_name"
+puts $fout "----------------------------------------"
+foreach {errtype coordlist} $drcresult {
+ puts $fout $errtype
+ puts $fout "----------------------------------------"
+ foreach coord $coordlist {
+ set bllx [expr {$oscale * [lindex $coord 0]}]
+ set blly [expr {$oscale * [lindex $coord 1]}]
+ set burx [expr {$oscale * [lindex $coord 2]}]
+ set bury [expr {$oscale * [lindex $coord 3]}]
+ set coords [format " %.3f %.3f %.3f %.3f" $bllx $blly $burx $bury]
+ puts $fout "$coords"
+ set count [expr {$count + 1} ]
+ }
+ puts $fout "----------------------------------------"
+}
+
+puts $fout "\[INFO\]: COUNT: $count"
+puts $fout "\[INFO\]: Should be divided by 3 or 4"
+
+puts $fout ""
+close $fout
+
+puts stdout "\[INFO\]: COUNT: $count"
+puts stdout "\[INFO\]: Should be divided by 3 or 4"
+puts stdout "\[INFO\]: DRC Checking DONE ($::env(OUT_DIR)/$::env(DESIGN_NAME).magic.drc)"
+flush stdout
+
+puts stdout "\[INFO\]: Saving mag view with DRC errors($::env(OUT_DIR)/$::env(DESIGN_NAME).magic.drc.mag)"
+# WARNING: changes the name of the cell; keep as last step
+save $::env(OUT_DIR)/$::env(DESIGN_NAME).magic.drc.mag
+puts stdout "\[INFO\]: Saved"
+
+exit 0
diff --git a/caravel/utils/core_scripts/magic-ext.sh b/caravel/utils/core_scripts/magic-ext.sh
new file mode 100644
index 0000000..68bfc39
--- /dev/null
+++ b/caravel/utils/core_scripts/magic-ext.sh
@@ -0,0 +1,36 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+# To call: ./magic-ext.sh <target_path> <design_name> <pdk-root> <target-type> <pdk-name> <output_path>
+
+export TARGET_DIR=$1
+export DESIGN_NAME=$2
+export PDK_ROOT=$3
+export TARGET_TYPE=$4
+export PDK=$5
+export OUT_DIR=$6
+export TCL_CALL_PATH=${7:-$(pwd)}
+
+echo "Running Magic..."
+export MAGIC_MAGICRC=$PDK_ROOT/$PDK/libs.tech/magic/sky130A.magicrc
+
+magic \
+ -noconsole \
+ -dnull \
+ -rcfile $MAGIC_MAGICRC \
+ $TCL_CALL_PATH/magic-ext.tcl \
+ </dev/null \
+ |& tee $OUT_DIR/magic_ext.log
diff --git a/caravel/utils/core_scripts/magic-ext.tcl b/caravel/utils/core_scripts/magic-ext.tcl
new file mode 100644
index 0000000..5a05dcb
--- /dev/null
+++ b/caravel/utils/core_scripts/magic-ext.tcl
@@ -0,0 +1,44 @@
+#!/usr/bin/tclsh
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+
+puts "Performing Spice Extractions..."
+
+if { ![file isdirectory $::env(OUT_DIR)] } {
+ exec mkdir $::env(OUT_DIR)/
+}
+
+
+if { $::env(TARGET_TYPE) == "gds"} {
+ gds read $::env(TARGET_DIR)/$::env(DESIGN_NAME).gds
+} else {
+ if { $::env(TARGET_TYPE) == "mag" } {
+ load $::env(TARGET_DIR)/$::env(DESIGN_NAME).mag
+ } else {
+ def read $::env(TARGET_DIR)/$::env(DESIGN_NAME).def
+ }
+}
+
+load $::env(DESIGN_NAME) -dereference
+cd $::env(OUT_DIR)/
+extract do local
+# extract warn all
+extract
+ext2spice lvs
+ext2spice $::env(DESIGN_NAME).ext
+feedback save $::env(OUT_DIR)/magic_extraction_feedback.txt
+
+puts "Done!"
\ No newline at end of file
diff --git a/caravel/utils/drc-def-sky130A.sh b/caravel/utils/drc-def-sky130A.sh
new file mode 100644
index 0000000..671b14a
--- /dev/null
+++ b/caravel/utils/drc-def-sky130A.sh
@@ -0,0 +1,29 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+# To call: ./drc-def-sky130A.sh <target_path> <design_name> <pdk-root> [<output_path> default is <target_path>/results/]
+
+export TARGET_DIR=$1
+export DESIGN_NAME=$2
+export PDK_ROOT=$3
+export OUT_DIR=${4:-$TARGET_DIR/results/}
+export TCL_CALL_PATH=$(pwd)/core_scripts
+
+if ! [[ -d "$OUT_DIR" ]]
+then
+ mkdir $OUT_DIR
+fi
+bash ./core_scripts/magic-drc.sh $TARGET_DIR $DESIGN_NAME $PDK_ROOT "def" "sky130A" $OUT_DIR $TCL_CALL_PATH
diff --git a/caravel/utils/drc-gds-sky130A.sh b/caravel/utils/drc-gds-sky130A.sh
new file mode 100644
index 0000000..4c1d6d8
--- /dev/null
+++ b/caravel/utils/drc-gds-sky130A.sh
@@ -0,0 +1,30 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+# To call: ./drc-gds-sky130A.sh <target_path> <design_name> <pdk-root> [<output_path> default is <target_path>/results/]
+
+export TARGET_DIR=$1
+export DESIGN_NAME=$2
+export PDK_ROOT=$3
+export OUT_DIR=${4:-$TARGET_DIR/results/}
+export TCL_CALL_PATH=$(pwd)/core_scripts
+
+if ! [[ -d "$OUT_DIR" ]]
+then
+ mkdir $OUT_DIR
+fi
+
+bash ./core_scripts/magic-drc.sh $TARGET_DIR $DESIGN_NAME $PDK_ROOT "gds" "sky130A" $OUT_DIR $TCL_CALL_PATH
diff --git a/caravel/utils/drc-mag-sky130A.sh b/caravel/utils/drc-mag-sky130A.sh
new file mode 100644
index 0000000..2bbecd3
--- /dev/null
+++ b/caravel/utils/drc-mag-sky130A.sh
@@ -0,0 +1,29 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+# To call: ./drc-mag-sky130A.sh <target_path> <design_name> <pdk-root> [<output_path> default is <target_path>/results/]
+
+export TARGET_DIR=$1
+export DESIGN_NAME=$2
+export PDK_ROOT=$3
+export OUT_DIR=${4:-$TARGET_DIR/results/}
+export TCL_CALL_PATH=$(pwd)/core_scripts
+
+if ! [[ -d "$OUT_DIR" ]]
+then
+ mkdir $OUT_DIR
+fi
+bash ./core_scripts/magic-drc.sh $TARGET_DIR $DESIGN_NAME $PDK_ROOT "mag" "sky130A" $OUT_DIR $TCL_CALL_PATH
diff --git a/caravel/utils/erase_box.sh b/caravel/utils/erase_box.sh
new file mode 100644
index 0000000..7636e42
--- /dev/null
+++ b/caravel/utils/erase_box.sh
@@ -0,0 +1,42 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+: ${1?"Usage: $0 file.gds llx lly urx ury"}
+: ${2?"Usage: $0 file.gds llx lly urx ury"}
+: ${3?"Usage: $0 file.gds llx lly urx ury"}
+: ${4?"Usage: $0 file.gds llx lly urx ury"}
+: ${5?"Usage: $0 file.gds llx lly urx ury"}
+: ${PDK_ROOT?"You need to export PDK_ROOT"}
+
+
+export PDK=sky130A
+
+export MAGIC_MAGICRC=$PDK_ROOT/$PDK/libs.tech/magic/$PDK.magicrc
+
+MAGTYPE=mag magic -rcfile $MAGIC_MAGICRC -dnull -noconsole <<EOF
+echo $MAGTYPE
+tech unlock *
+gds read $1
+box $2um $3um $4um $5um
+erase
+select area
+delete
+#### REVISE THIS:
+select top cell
+erase labels
+####
+gds write ${1%.*}_erased.gds
+EOF
+ls ${1%.*}_erased.gds
diff --git a/caravel/utils/examples/README.md b/caravel/utils/examples/README.md
new file mode 100644
index 0000000..10f7a37
--- /dev/null
+++ b/caravel/utils/examples/README.md
@@ -0,0 +1,19 @@
+<!---
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+-->
+This folder contains miscelleneous useful scripts
+THIS IS STILL WORK IN PROGRESSS - SUGGESTIONS ARE WELCOME THROUGH ISSUES
diff --git a/caravel/utils/examples/addmpwseal.tcl b/caravel/utils/examples/addmpwseal.tcl
new file mode 100644
index 0000000..79e4b9e
--- /dev/null
+++ b/caravel/utils/examples/addmpwseal.tcl
@@ -0,0 +1,26 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+drc off
+gds readonly true
+gds read ../gds/sram_1rw1r_32_256_8_sky130_lp1.gds
+load openram_tc_1kb.mag
+select top cell
+move origin -1015um -1272.5um
+box position 0 0
+getcell advSeal_6um_gen
+save
+gds write ../gds/openram_tc_1kb.gds
+
diff --git a/caravel/utils/examples/create-project.sh b/caravel/utils/examples/create-project.sh
new file mode 100644
index 0000000..5b5b69c
--- /dev/null
+++ b/caravel/utils/examples/create-project.sh
@@ -0,0 +1,38 @@
+#!/bin/sh
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+cat <<'EOT' > .gitignore
+.DS_Store
+*.vcd
+*.raw
+*.vvp
+a.out
+EOT
+mkdir scripts ; echo "This folder contains miscelleneous useful scripts" > scripts/README.md
+mkdir def ; echo "This folder contains *.def files related to this project" > def/README.md
+mkdir gds ; echo "This folder contains *.gds files related to this project" > gds/README.md
+mkdir verilog ; echo "This folder contains *.v files related to this project" > verilog/README.md
+mkdir mag ; echo "This folder contains *.mag files related to this project" > mag/README.md
+mkdir lef ; echo "This folder contains *.lef files related to this project" > lef/README.md
+mkdir macros ; echo "This folder contains subcell & macro files related to this project" > macros/README.md
+mkdir doc ; echo "This folder contains documents related to this project" > doc/README.md
+mkdir ngspice ; echo "This folder contains ngspice related files related to this project" > ngspice/README.md
+mkdir openlane ; echo "This folder contains openlane related files related to this project" > openlane/README.md
+mkdir pkg ; echo "This folder contains packaging-related files related to this project" > pkg/README.md
+mkdir test ; echo "This folder contains test-related files related to this project" > test/README.md
+mkdir xspice ; echo "This folder contains xspice files related to this project" > xspice/README.md
+mkdir spi ; echo "This folder contains *.spi files related to this project" > spi/README.md
+mkdir qflow ; echo "This folder contains qflow-related files related to this project" > qflow/README.md
diff --git a/caravel/utils/examples/dot.magicrc b/caravel/utils/examples/dot.magicrc
new file mode 100644
index 0000000..42f2fb2
--- /dev/null
+++ b/caravel/utils/examples/dot.magicrc
@@ -0,0 +1,65 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+
+puts stdout "Sourcing design .magicrc for technology sky130A ..."
+
+# Put grid on 0.005 pitch. This is important, as some commands don't
+# rescale the grid automatically (such as lef read?).
+
+set scalefac [tech lambda]
+if {[lindex $scalefac 1] < 2} {
+ scalegrid 1 2
+}
+
+# drc off
+drc euclidean on
+
+# default pdk
+# set SW_PDK_ROOT "/ef/tech/SW.2"
+set PDK "sky130A"
+set SCL_VARIANT "sky130_fd_sc_hd"
+set IO_VARIANT "sky130_fd_io"
+set PDKPATH "$::env(SW_PDK_ROOT)/$PDK"
+
+# loading technology
+tech load "$PDKPATH/libs.tech/magic/current/$PDK.tech"
+
+# load device generator
+source "$PDKPATH/libs.tech/magic/current/$PDK.tcl"
+
+
+# load bind keys (optional)
+source "$PDKPATH/libs.tech/magic/current/$PDK-BindKeys"
+
+# set units to lambda grid
+snap lambda
+
+# add path to reference cells
+set MAGPATH "$PDKPATH/libs.ref/$SCL_VARIANT/mag/*.mag"
+
+
+addpath "$PDKPATH/libs.ref/sky130_fd_pr_base/mag"
+addpath "$PDKPATH/libs.ref/$IO_VARIANT/mag"
+addpath "$PDKPATH/libs.ref/$SCL_VARIANT/mag"
+
+# addpath ${MAGPATH}/s8fmlt
+
+# add path to GDS cells
+
+# add path to IP from catalog. This procedure defined in the PDK script.
+catch {magic::query_mylib_ip}
+# add path to local IP from user design space. Defined in the PDK script.
+catch {magic::query_my_projects}
diff --git a/caravel/utils/examples/drc-mag.sh b/caravel/utils/examples/drc-mag.sh
new file mode 100644
index 0000000..7229f45
--- /dev/null
+++ b/caravel/utils/examples/drc-mag.sh
@@ -0,0 +1,40 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+
+export MAGTYPE=mag ;
+export BASE=/home/mk/zooz/ ;
+export PDKPATH=$BASE/pdks/ef-skywater-s8/EFS8A ;
+
+magic -dnull -noconsole -rcfile $PDKPATH/libs.tech/magic/current/EFS8A.magicrc <<EOF
+gds polygon subcell true
+gds warning default
+gds read $1.gds
+load $1
+cellname delete \(UNNAMED\)
+writeall force
+select top cell
+expand
+drc on
+drc euclidean on
+drc check
+drc catchup
+drc listall
+drc listall why
+drc count total
+drc count
+quit -noprompt
+EOF
diff --git a/caravel/utils/examples/drc-maglef.sh b/caravel/utils/examples/drc-maglef.sh
new file mode 100644
index 0000000..42f622f
--- /dev/null
+++ b/caravel/utils/examples/drc-maglef.sh
@@ -0,0 +1,40 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+
+export MAGTYPE=maglef ;
+export BASE=/home/mk/zooz/ ;
+export PDKPATH=$BASE/pdks/ef-skywater-s8/EFS8A ;
+
+magic -dnull -noconsole -rcfile $PDKPATH/libs.tech/magic/current/EFS8A.magicrc <<EOF
+gds polygon subcell true
+gds warning default
+gds read $1.gds
+load $1
+cellname delete \(UNNAMED\)
+writeall force
+select top cell
+expand
+drc on
+drc euclidean on
+drc check
+drc catchup
+drc listall
+drc listall why
+drc count total
+drc count
+quit -noprompt
+EOF
diff --git a/caravel/utils/examples/drc.sh b/caravel/utils/examples/drc.sh
new file mode 100644
index 0000000..7229f45
--- /dev/null
+++ b/caravel/utils/examples/drc.sh
@@ -0,0 +1,40 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+
+export MAGTYPE=mag ;
+export BASE=/home/mk/zooz/ ;
+export PDKPATH=$BASE/pdks/ef-skywater-s8/EFS8A ;
+
+magic -dnull -noconsole -rcfile $PDKPATH/libs.tech/magic/current/EFS8A.magicrc <<EOF
+gds polygon subcell true
+gds warning default
+gds read $1.gds
+load $1
+cellname delete \(UNNAMED\)
+writeall force
+select top cell
+expand
+drc on
+drc euclidean on
+drc check
+drc catchup
+drc listall
+drc listall why
+drc count total
+drc count
+quit -noprompt
+EOF
diff --git a/caravel/utils/examples/edit.tcl b/caravel/utils/examples/edit.tcl
new file mode 100644
index 0000000..f1766ad
--- /dev/null
+++ b/caravel/utils/examples/edit.tcl
@@ -0,0 +1,26 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+drc off
+puts "Small delay..."
+set macro_mags "digital_pll.mag lvlshiftdown.mag striVe2_soc.mag striVe_clkrst.mag striVe_spi.mag"
+
+gds readonly yes
+gds rescale no
+gds read ../gds/sram_1rw1r_32_256_8_sky130.gds
+lef read ../lef/sram.abs.lef
+foreach ff $macro_mags { drc off; load $ff -dereference; after 1000; select top cell; property LEFview TRUE }
+load striVe2 -dereference
+select top cell
diff --git a/caravel/utils/examples/ext-gds.sh b/caravel/utils/examples/ext-gds.sh
new file mode 100644
index 0000000..c3efd7e
--- /dev/null
+++ b/caravel/utils/examples/ext-gds.sh
@@ -0,0 +1,43 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+
+export MAGTYPE=maglef ;
+export BASE=/home/mk/zooz/ ;
+export PDKPATH=$BASE/pdks/ef-skywater-s8/EFS8A ;
+
+magic -dnull -noconsole -rcfile $PDKPATH/libs.tech/magic/current/EFS8A.magicrc <<EOF
+gds polygon subcell true
+gds warning default
+gds read $1.gds
+load $1.mag
+save $1.mag
+writeall force
+select top cell
+extract style ngspice(si)
+extract
+ext2spice hierarchy on
+ext2spice format ngspice
+ext2spice cthresh infinite
+ext2spice rthresh infinite
+ext2spice renumber offS
+ext2spice scale off
+ext2spice blackbox on
+ext2spice subcircuit top auto
+ext2spice global off
+ext2spice $1.ext
+quit -noprompt
+EOF
diff --git a/caravel/utils/examples/ext-mag.sh b/caravel/utils/examples/ext-mag.sh
new file mode 100644
index 0000000..a62a831
--- /dev/null
+++ b/caravel/utils/examples/ext-mag.sh
@@ -0,0 +1,40 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+
+export MAGTYPE=mag ;
+export BASE=/home/mk/zooz/ ;
+export PDKPATH=$BASE/pdks/ef-skywater-s8/EFS8A ;
+
+magic -dnull -noconsole -rcfile $PDKPATH/libs.tech/magic/current/EFS8A.magicrc <<EOF
+load $1.mag
+save $1.mag
+writeall force
+select top cell
+extract style ngspice(si)
+extract
+ext2spice hierarchy on
+ext2spice format ngspice
+ext2spice cthresh infinite
+ext2spice rthresh infinite
+ext2spice renumber offS
+ext2spice scale off
+ext2spice blackbox on
+ext2spice subcircuit top auto
+ext2spice global off
+ext2spice $1.ext
+quit -noprompt
+EOF
diff --git a/caravel/utils/examples/ext.sh b/caravel/utils/examples/ext.sh
new file mode 100644
index 0000000..b414e8b
--- /dev/null
+++ b/caravel/utils/examples/ext.sh
@@ -0,0 +1,43 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+
+export MAGTYPE=maglef ;
+export BASE=/home/mk/zooz/ ;
+export PDKPATH=$BASE/pdks/ef-skywater-s8/EFS8A ;
+
+magic -dnull -noconsole -rcfile $PDKPATH/libs.tech/magic/current/EFS8A.magicrc <<EOF
+gds polygon subcell true
+gds warning default
+gds read $1.gds
+load $1.mag
+save $1.mag
+writeall force
+select top cell
+extract style ngspice(si)
+extract
+ext2spice hierarchy on
+ext2spice format ngspice
+ext2spice cthresh infinite
+ext2spice rthresh infinite
+ext2spice renumber off
+ext2spice scale off
+ext2spice blackbox on
+ext2spice subcircuit top auto
+ext2spice global off
+ext2spice $1.ext
+quit -noprompt
+EOF
diff --git a/caravel/utils/examples/extract.tcl b/caravel/utils/examples/extract.tcl
new file mode 100644
index 0000000..a38c9cb
--- /dev/null
+++ b/caravel/utils/examples/extract.tcl
@@ -0,0 +1,31 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+lef read $::env(PDKPATH)/libs.ref/techLEF/scs8hd/scs8hd_tech.lef
+set macro_mags "openram_tc_core.mag"
+
+# lef read ../lef/sram_1rw1r_32_256_8_sky130_lp1.lef
+
+foreach ff $macro_mags { drc off; after 500; load $ff -dereference; select top cell; property LEFview TRUE }
+
+load openram_tc_1kb -dereference
+
+select top cell
+extract do local
+extract
+ext2spice lvs
+ext2spice openram_tc_1kb.ext
+feedback save extract.tcl.log
+exit
diff --git a/caravel/utils/examples/lvs.sh b/caravel/utils/examples/lvs.sh
new file mode 100644
index 0000000..3a5043e
--- /dev/null
+++ b/caravel/utils/examples/lvs.sh
@@ -0,0 +1,22 @@
+#!/bin/sh
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+/ef/apps/bin/netgen -noconsole << EOF
+readnet spice $1.spice
+readnet spice $1.sp
+lvs {$1.spice sram_2_16_sky130} {sram_2_16_sky130.sp sram_2_16_sky130} setup.tcl sram_2_16_sky130.lvs.report
+quit
+EOF
diff --git a/caravel/utils/examples/mag2gds.tcl b/caravel/utils/examples/mag2gds.tcl
new file mode 100644
index 0000000..8d7057d
--- /dev/null
+++ b/caravel/utils/examples/mag2gds.tcl
@@ -0,0 +1,33 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+# assumes an /ef tree or at least a symlink
+drc off
+gds readonly true
+gds rescale false
+set ::env(MAGTYPE) mag
+
+# gds read <hard macros read as-is.gds>
+gds read ../gds/sram_1rw1r_32_256_8_sky130_lp1.gds
+
+load sram_1rw1r_32_256_8_sky130 -dereference
+load openram_tc_core -dereference
+load openram_tc_1kb -dereference
+
+select top cell
+
+cif *hier write disable
+
+gds write openram_tc_1kb.gds
diff --git a/caravel/utils/examples/magic_drc.tcl b/caravel/utils/examples/magic_drc.tcl
new file mode 100644
index 0000000..554a4c6
--- /dev/null
+++ b/caravel/utils/examples/magic_drc.tcl
@@ -0,0 +1,71 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+set ::env(DESIGN_NAME) openram_tc_1kb
+drc off
+lef read ../lef/sram_1rw1r_32_256_8_sky130_lp1.lef
+load sram_1rw1r_32_256_8_sky130 -dereference
+load openram_tc_core -dereference
+load openram_tc_1kb -dereference
+
+drc style drc(full)
+drc euclidean on
+
+set fout [open drc.log w]
+set oscale [cif scale out]
+set cell_name $::env(DESIGN_NAME)
+magic::suspendall
+puts stdout "\[INFO\]: Loading $cell_name\n"
+flush stdout
+load $cell_name
+select top cell
+drc check
+set drcresult [drc listall why]
+
+
+set count 0
+puts $fout "$cell_name"
+puts $fout "----------------------------------------"
+foreach {errtype coordlist} $drcresult {
+ puts $fout $errtype
+ puts $fout "----------------------------------------"
+ foreach coord $coordlist {
+ set bllx [expr {$oscale * [lindex $coord 0]}]
+ set blly [expr {$oscale * [lindex $coord 1]}]
+ set burx [expr {$oscale * [lindex $coord 2]}]
+ set bury [expr {$oscale * [lindex $coord 3]}]
+ set coords [format " %.3f %.3f %.3f %.3f" $bllx $blly $burx $bury]
+ puts $fout "$coords"
+ set count [expr {$count + 1} ]
+ }
+ puts $fout "----------------------------------------"
+}
+
+puts $fout "\[INFO\]: COUNT: $count"
+puts $fout "\[INFO\]: Should be divided by 3 or 4"
+
+puts $fout ""
+close $fout
+
+puts stdout "\[INFO\]: COUNT: $count"
+puts stdout "\[INFO\]: Should be divided by 3 or 4"
+puts stdout "\[INFO\]: DRC Checking DONE ($::env(DESIGN_NAME).drc)"
+flush stdout
+
+puts stdout "\[INFO\]: Saving mag view with DRC errors($::env(DESIGN_NAME).drc.mag)"
+# WARNING: changes the name of the cell; keep as last step
+save $::env(DESIGN_NAME).drc.mag
+puts stdout "\[INFO\]: Saved"
+
+exit 0
diff --git a/caravel/utils/examples/pfg.sh b/caravel/utils/examples/pfg.sh
new file mode 100644
index 0000000..9d8def1
--- /dev/null
+++ b/caravel/utils/examples/pfg.sh
@@ -0,0 +1,38 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+
+export PDKPATH=/home/mk/zooz/pdks/ef-skywater-s8/EFS8A
+export MAGTYPE=mag
+
+padring \
+-L $PDKPATH/libs.ref/lef/s8iom0s8/s8iom0s8.lef \
+-L $PDKPATH/libs.ref/lef/s8iom0s8/power_pads_lib.lef \
+--def padframe.def padframe.cfg
+
+magic -rcfile $PDKPATH/libs.tech/magic/current/EFS8A.magicrc -noc -dnull <<EOF
+def read padframe.def
+save padframe
+select top cell
+lef write padframe.lef
+gds write padframe.gds
+exit
+EOF
+
+
+
+
+
diff --git a/caravel/utils/examples/run_openram_tc_1kb.sh b/caravel/utils/examples/run_openram_tc_1kb.sh
new file mode 100644
index 0000000..408ce96
--- /dev/null
+++ b/caravel/utils/examples/run_openram_tc_1kb.sh
@@ -0,0 +1,23 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+#
+# Run netgen on striVe (top level)
+#
+
+NETGEN_SETUP=$PDK_ROOT/EFS8A/libs.tech/netgen/EFS8A_setup.tcl
+
+netgen -batch lvs "../spi/openram_tc_1kb.spice openram_tc_1kb" "../verilog/gl/openram_tc_1kb.synthesis.v openram_tc_1kb" ${NETGEN_SETUP} openram_tc_1kb_comp.out -json | tee openram_tc_1kb_comp_lvs.log
diff --git a/caravel/utils/examples/setup.tcl b/caravel/utils/examples/setup.tcl
new file mode 100644
index 0000000..193dd2f
--- /dev/null
+++ b/caravel/utils/examples/setup.tcl
@@ -0,0 +1,27 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+# We must flatten these because the ports are disconnected
+flatten class {-circuit1 dummy_cell_6t}
+flatten class {-circuit1 dummy_cell_1rw_1r}
+flatten class {-circuit1 dummy_cell_1w_1r}
+flatten class {-circuit1 bitcell_array_0}
+flatten class {-circuit1 pbitcell_0}
+flatten class {-circuit1 pbitcell_1}
+property {-circuit1 nshort} remove as ad ps pd
+property {-circuit1 pshort} remove as ad ps pd
+property {-circuit2 nshort} remove as ad ps pd
+property {-circuit2 pshort} remove as ad ps pd
+permute transistors
diff --git a/caravel/utils/examples/wrap.tcl b/caravel/utils/examples/wrap.tcl
new file mode 100644
index 0000000..fc2c87e
--- /dev/null
+++ b/caravel/utils/examples/wrap.tcl
@@ -0,0 +1,28 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+drc off
+gds readonly yes
+gds rescale no
+
+gds read ../macros/sram/riscv-sky130/sram_1rw1r_32_256_8_sky130.gds
+load sram_1rw1r_32_256_8_sky130
+
+select top cell
+property LEFview "TRUE"
+
+save pk_sram_1rw1r_32_256_8_sky130.mag
+
+# exec sed -i -E "/^.*GDS_END.*$/d" sram_1rw1r_32_256_8_sky130_original.mag
diff --git a/caravel/utils/examples/wrap2.tcl b/caravel/utils/examples/wrap2.tcl
new file mode 100644
index 0000000..db1db3c
--- /dev/null
+++ b/caravel/utils/examples/wrap2.tcl
@@ -0,0 +1,36 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+drc off
+gds readonly yes
+gds rescale no
+
+lef read ../lef/sram.abs.con.lef
+load sram_1rw1r_32_256_8_sky130
+
+select top cell
+expand
+property LEFview ""
+property LEFsymmetry ""
+property LEFclass ""
+
+box position 5um 5um
+getcell pk_sram_1rw1r_32_256_8_sky130
+
+save sram_1rw1r_32_256_8_sky130.mag
+
+gds write output.gds
+
+save
diff --git a/caravel/utils/examples/xor.drc b/caravel/utils/examples/xor.drc
new file mode 100644
index 0000000..14896ee
--- /dev/null
+++ b/caravel/utils/examples/xor.drc
@@ -0,0 +1,42 @@
+# A general XOR script
+# (https://www.klayout.de/forum/discussion/100/xor-vs-diff-tool)
+# This script uses KLayout's DRC language to implement a generic
+# XOR between two layouts. The name of the layouts is given
+# in $a and $b.
+
+# For layout-to-layout XOR with multiple cores, run this script with
+# ./klayout -r xor.drc -rd thr=NUM_CORES -rd top_cell=TOP_CELL_NAME -rd a=a.gds -rd b=b.gds -rd ol=xor.gds -zz
+# (replace NUM_CORES by the desired number of cores to utilize
+
+# enable timing output
+verbose
+
+# set up input a
+a = source($a, $top_cell)
+
+# set up input b
+b = source($b, $top_cell)
+
+$o && report("XOR #{$a} vs. #{$b}", $o)
+$ol && target($ol, $co || "XOR")
+
+$thr && threads($thr) || threads(2)
+
+# collect all common layers
+layers = {}
+[ a.layout, b.layout ].each do |ly|
+ ly.layer_indices.each do |li|
+ i = ly.get_info(li)
+ layers[i.to_s] = i
+ end
+end
+
+# perform the XOR's
+layers.keys.sort.each do |l|
+ i = layers[l]
+ info("--- Running XOR for #{l} ---")
+ x = a.input(l) ^ b.input(l)
+ info("XOR differences: #{x.data.size}")
+ $o && x.output(l, "XOR results for layer #{l}")
+ $ol && x.output(i.layer, i.datatype, i.name)
+end
diff --git a/caravel/utils/examples/xor.sh b/caravel/utils/examples/xor.sh
new file mode 100644
index 0000000..6911062
--- /dev/null
+++ b/caravel/utils/examples/xor.sh
@@ -0,0 +1,22 @@
+#!/bin/sh
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+
+: ${1?"Usage: $0 file1.gds file2.gds <top_level_module_name>"}
+: ${2?"Usage: $0 file1.gds file2.gds <top_level_module_name>"}
+: ${3?"Usage: $0 file1.gds file2.gds <top_level_module_name>"}
+
+klayout -r $(dirname $0)/xor.drc -rd top_cell=$3 -rd a=$1 -rd b=$2 -rd thr=$(nproc) -rd ol=xor.gds -zz
diff --git a/caravel/utils/ext-def-sky130A.sh b/caravel/utils/ext-def-sky130A.sh
new file mode 100644
index 0000000..51ec955
--- /dev/null
+++ b/caravel/utils/ext-def-sky130A.sh
@@ -0,0 +1,30 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+# To call: ./ext-def-sky130A.sh <target_path> <design_name> <pdk-root> [<output_path> default is <target_path>/results/]
+
+export TARGET_DIR=$1
+export DESIGN_NAME=$2
+export PDK_ROOT=$3
+export OUT_DIR=${4:-$TARGET_DIR/results/}
+export TCL_CALL_PATH=$(pwd)/core_scripts
+
+if ! [[ -d "$OUT_DIR" ]]
+then
+ mkdir $OUT_DIR
+fi
+
+bash ./core_scripts/magic-ext.sh $TARGET_DIR $DESIGN_NAME $PDK_ROOT "def" "sky130A" $OUT_DIR $TCL_CALL_PATH
diff --git a/caravel/utils/ext-gds-sky130A.sh b/caravel/utils/ext-gds-sky130A.sh
new file mode 100644
index 0000000..35071b8
--- /dev/null
+++ b/caravel/utils/ext-gds-sky130A.sh
@@ -0,0 +1,30 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+# To call: ./ext-gds-sky130A.sh <target_path> <design_name> <pdk-root> [<output_path> default is <target_path>/results/]
+
+export TARGET_DIR=$1
+export DESIGN_NAME=$2
+export PDK_ROOT=$3
+export OUT_DIR=${4:-$TARGET_DIR/results/}
+export TCL_CALL_PATH=$(pwd)/core_scripts
+
+if ! [[ -d "$OUT_DIR" ]]
+then
+ mkdir $OUT_DIR
+fi
+
+bash ./core_scripts/magic-ext.sh $TARGET_DIR $DESIGN_NAME $PDK_ROOT "gds" "sky130A" $OUT_DIR $TCL_CALL_PATH
diff --git a/caravel/utils/ext-mag-sky130A.sh b/caravel/utils/ext-mag-sky130A.sh
new file mode 100644
index 0000000..b57ec31
--- /dev/null
+++ b/caravel/utils/ext-mag-sky130A.sh
@@ -0,0 +1,30 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+# To call: ./ext-mag-sky130A.sh <target_path> <design_name> <pdk-root> [<output_path> default is <target_path>/results/]
+
+export TARGET_DIR=$1
+export DESIGN_NAME=$2
+export PDK_ROOT=$3
+export OUT_DIR=${4:-$TARGET_DIR/results/}
+export TCL_CALL_PATH=$(pwd)/core_scripts
+
+if ! [[ -d "$OUT_DIR" ]]
+then
+ mkdir $OUT_DIR
+fi
+
+bash ./core_scripts/magic-ext.sh $TARGET_DIR $DESIGN_NAME $PDK_ROOT "mag" "sky130A" $OUT_DIR $TCL_CALL_PATH
diff --git a/caravel/utils/gds2mag-mag.local.sh b/caravel/utils/gds2mag-mag.local.sh
new file mode 100644
index 0000000..110358b
--- /dev/null
+++ b/caravel/utils/gds2mag-mag.local.sh
@@ -0,0 +1,37 @@
+#!/bin/sh
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+export PDK_ROOT=~/foss/pdks/open_pdks/sky130;
+export MAGTYPE=mag ;
+export PDKPATH=$PDK_ROOT/sky130A ;
+export MAGIC=magic
+
+
+$MAGIC -dnull -noconsole << EOF
+#------------------------------------------------------
+drc off
+#---------------------------------gds polygon subcell true
+gds warning default
+gds readonly true
+gds rescale false
+#---------------------------------tech unlock *
+gds read $1
+load ${1%.gds}
+#---------------------------------readspice ${1%.gds}.sp
+cellname delete "(UNNAMED)"
+save ${1%.gds}.mag
+quit -noprompt
+EOF
diff --git a/caravel/utils/gds2mag-mag.sh b/caravel/utils/gds2mag-mag.sh
new file mode 100644
index 0000000..d53b156
--- /dev/null
+++ b/caravel/utils/gds2mag-mag.sh
@@ -0,0 +1,37 @@
+#!/bin/sh
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+export PDK_ROOT=~/foss/pdks/open_pdks/sky130;
+export MAGTYPE=mag ;
+export PDKPATH=$PDK_ROOT/sky130A ;
+export MAGIC=magic
+
+
+$MAGIC -rcfile $PDKPATH/libs.tech/magic/current/sky130A.magicrc -dnull -noconsole << EOF
+#------------------------------------------------------
+drc off
+#---------------------------------gds polygon subcell true
+gds warning default
+gds readonly true
+gds rescale false
+#---------------------------------tech unlock *
+gds read $1
+load ${1%.gds}
+#---------------------------------readspice ${1%.gds}.sp
+cellname delete "(UNNAMED)"
+save ${1%.gds}.mag
+quit -noprompt
+EOF
diff --git a/caravel/utils/lef2maglef.sh b/caravel/utils/lef2maglef.sh
new file mode 100644
index 0000000..455c4a6
--- /dev/null
+++ b/caravel/utils/lef2maglef.sh
@@ -0,0 +1,60 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+
+export PDK_ROOT=~/foss/pdks/open_pdks/sky130;
+export MAGTYPE=mag ;
+export PDKPATH=$PDK_ROOT/sky130A ;
+export MAGIC=magic
+
+
+$MAGIC -rcfile $PDKPATH/libs.tech/magic/current/sky130A.magicrc -dnull -noconsole << EOX
+drc off
+lef read $1.lef
+load $1
+save $1.lef.mag
+#writeall force $1.lef.mag
+
+ # copy GDS properties from the MAG view into the MAGLEF view
+ set gds_properties [list]
+ set fp [open $1.mag r]
+ set mag_lines [split [read \$fp] "\n"]
+ foreach line \$mag_lines {
+ if { [string first "string GDS_" \$line] != -1 } {
+ lappend gds_properties \$line
+ }
+ }
+ close \$fp
+ set fp [open $1.lef.mag r]
+ set mag_lines [split [read \$fp] "\n"]
+ set new_mag_lines [list]
+ foreach line \$mag_lines {
+ if { [string first "<< end >>" \$line] != -1 } {
+ lappend new_mag_lines [join \$gds_properties "\n"]
+ }
+ lappend new_mag_lines \$line
+ }
+ close \$fp
+ set fp [open $1.lef.mag w]
+ puts \$fp [join \$new_mag_lines "\n"]
+ close \$fp
+
+
+quit
+EOX
+
+mv -f $1.lef.mag ../maglef/$1.mag
+rm -f $1.lef
diff --git a/caravel/utils/mag2maglef-mag.sh b/caravel/utils/mag2maglef-mag.sh
new file mode 100644
index 0000000..2934887
--- /dev/null
+++ b/caravel/utils/mag2maglef-mag.sh
@@ -0,0 +1,68 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+
+export PDK_ROOT=~/foss/pdks/open_pdks/sky130;
+export MAGTYPE=mag ;
+export PDKPATH=$PDK_ROOT/sky130A ;
+export MAGIC=magic
+
+$MAGIC -rcfile $PDKPATH/libs.tech/magic/current/sky130A.magicrc -dnull -noconsole <<EOF
+drc off
+load $1.mag
+select top cell
+expand
+lef write $1.lef -hide
+quit -noprompt
+EOF
+
+$MAGIC -rcfile $PDKPATH/libs.tech/magic/current/sky130A.magicrc -dnull -noconsole << EOX
+drc off
+lef read $1.lef
+load $1
+save $1.lef.mag
+#writeall force $1.lef.mag
+
+ # copy GDS properties from the MAG view into the MAGLEF view
+ set gds_properties [list]
+ set fp [open $1.mag r]
+ set mag_lines [split [read \$fp] "\n"]
+ foreach line \$mag_lines {
+ if { [string first "string GDS_" \$line] != -1 } {
+ lappend gds_properties \$line
+ }
+ }
+ close \$fp
+ set fp [open $1.lef.mag r]
+ set mag_lines [split [read \$fp] "\n"]
+ set new_mag_lines [list]
+ foreach line \$mag_lines {
+ if { [string first "<< end >>" \$line] != -1 } {
+ lappend new_mag_lines [join \$gds_properties "\n"]
+ }
+ lappend new_mag_lines \$line
+ }
+ close \$fp
+ set fp [open $1.lef.mag w]
+ puts \$fp [join \$new_mag_lines "\n"]
+ close \$fp
+
+
+quit
+EOX
+
+mv -f $1.lef.mag ../maglef/$1.mag
+rm -f $1.lef
diff --git a/caravel/utils/mag2maglef-maglef.localrc.sh b/caravel/utils/mag2maglef-maglef.localrc.sh
new file mode 100644
index 0000000..f167252
--- /dev/null
+++ b/caravel/utils/mag2maglef-maglef.localrc.sh
@@ -0,0 +1,68 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+
+export PDK_ROOT=~/foss/pdks/open_pdks/sky130;
+export MAGTYPE=maglef ;
+export PDKPATH=$PDK_ROOT/sky130A ;
+export MAGIC=magic
+
+$MAGIC -dnull -noconsole <<EOF
+drc off
+load $1.mag
+select top cell
+expand
+lef write $1.lef -hide
+quit -noprompt
+EOF
+
+$MAGIC -dnull -noconsole << EOX
+drc off
+lef read $1.lef
+load $1
+save $1.lef.mag
+#writeall force $1.lef.mag
+
+ # copy GDS properties from the MAG view into the MAGLEF view
+ set gds_properties [list]
+ set fp [open $1.mag r]
+ set mag_lines [split [read \$fp] "\n"]
+ foreach line \$mag_lines {
+ if { [string first "string GDS_" \$line] != -1 } {
+ lappend gds_properties \$line
+ }
+ }
+ close \$fp
+ set fp [open $1.lef.mag r]
+ set mag_lines [split [read \$fp] "\n"]
+ set new_mag_lines [list]
+ foreach line \$mag_lines {
+ if { [string first "<< end >>" \$line] != -1 } {
+ lappend new_mag_lines [join \$gds_properties "\n"]
+ }
+ lappend new_mag_lines \$line
+ }
+ close \$fp
+ set fp [open $1.lef.mag w]
+ puts \$fp [join \$new_mag_lines "\n"]
+ close \$fp
+
+
+quit
+EOX
+
+mv -f $1.lef.mag ../maglef/$1.mag
+rm -f $1.lef
diff --git a/caravel/utils/mag2maglef-maglef.sh b/caravel/utils/mag2maglef-maglef.sh
new file mode 100644
index 0000000..e70fbd3
--- /dev/null
+++ b/caravel/utils/mag2maglef-maglef.sh
@@ -0,0 +1,68 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+
+export PDK_ROOT=~/foss/pdks/open_pdks/sky130;
+export MAGTYPE=maglef ;
+export PDKPATH=$PDK_ROOT/sky130A ;
+export MAGIC=magic
+
+$MAGIC -rcfile $PDKPATH/libs.tech/magic/current/sky130A.magicrc -dnull -noconsole <<EOF
+drc off
+load $1.mag
+select top cell
+expand
+lef write $1.lef
+quit -noprompt
+EOF
+
+$MAGIC -rcfile $PDKPATH/libs.tech/magic/current/sky130A.magicrc -dnull -noconsole << EOX
+drc off
+lef read $1.lef
+load $1
+save $1.lef.mag
+#writeall force $1.lef.mag
+
+ # copy GDS properties from the MAG view into the MAGLEF view
+ set gds_properties [list]
+ set fp [open $1.mag r]
+ set mag_lines [split [read \$fp] "\n"]
+ foreach line \$mag_lines {
+ if { [string first "string GDS_" \$line] != -1 } {
+ lappend gds_properties \$line
+ }
+ }
+ close \$fp
+ set fp [open $1.lef.mag r]
+ set mag_lines [split [read \$fp] "\n"]
+ set new_mag_lines [list]
+ foreach line \$mag_lines {
+ if { [string first "<< end >>" \$line] != -1 } {
+ lappend new_mag_lines [join \$gds_properties "\n"]
+ }
+ lappend new_mag_lines \$line
+ }
+ close \$fp
+ set fp [open $1.lef.mag w]
+ puts \$fp [join \$new_mag_lines "\n"]
+ close \$fp
+
+
+quit
+EOX
+
+mv -f $1.lef.mag ../maglef/$1.mag
+rm -f $1.lef
diff --git a/caravel/utils/magicDrc b/caravel/utils/magicDrc
new file mode 100644
index 0000000..fa6f783
--- /dev/null
+++ b/caravel/utils/magicDrc
@@ -0,0 +1,888 @@
+#!/bin/bash
+# SPDX-FileCopyrightText: 2015, 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+# Copyright (C) 2015, 2020 efabless Corporation. All Rights Reserved.
+# filter out most options, so magic Natively sees/handles *only* -T <file>.
+# for-bash\
+ declare -a C ; declare -a N ; export _CE= _NE= _M0= ;\
+ for i in "$@" ; do _M0="$_M0${_M0:+ }\"${i//\"/\\\"}\""; done ;\
+ while getopts "NFT:S:l:P:" o; do \
+ : echo got "optchar $o, with optarg $OPTARG" ;\
+ case "$o" in S) \
+ C+=(-${o} "$OPTARG") ;\
+ continue ; esac ;\
+ case "$o" in P) \
+ C+=(-${o} "$OPTARG") ;\
+ continue ; esac ;\
+ case "$o" in F|N) \
+ C+=(-${o}) ;\
+ continue ; esac ;\
+ case "$o" in l) \
+ C+=(-${o} "$OPTARG") ;\
+ continue ; esac ;\
+ case "$o" in T) \
+ N+=(-${o} "$OPTARG") ;\
+ continue ; esac ;\
+ done ;\
+ shift $((OPTIND-1)) ;\
+ for i in "${C[@]}" ; do _CE="$_CE${_CE:+ }\"${i//\"/\\\"}\""; done ;\
+ for i in "${N[@]}" ; do _NE="$_NE${_NE:+ }\"${i//\"/\\\"}\""; done ;\
+ exec magic -dnull -noconsole "${N[@]}" <"$0"
+# for-magic:
+# magicDrc: run magic-DRC in batch on a .mag file, tabulate/pareto the error counts.
+#
+# magicDrc [-T <techfilePath>] [-S <drcStyleName>] [-P <N> ] [-l FILE_NAME] <magFileName>
+# -T name specific techfile (def .tech extension), passed to magic itself only, overrides tech implied by magFileName
+# -S if given, changes from techfile's default drc style (perhaps "drc(fast)") to named style, for example: -S "drc(full)"
+# -l if given, enumerates EVERY individual error bbox to the FILE_NAME
+# -N if given, do Not use -dereference option of load for topcell (not available in older magics)
+# -F flatten top cell in-memory only, not saved (experimental)
+# -P do crude drc performance measurement. At top-cell, do 'drc find' <N> times and report time per call.
+# Stdout will log a pareto of error type by count regardless.
+#
+# <magFileName>: names a .mag file, the toplevel of the hier. to DRC/pareto
+#
+# Normal magic init. files are STILL sourced: ~/.magicrc and either $CWD/.magicrc or $CWD/magic_setup.
+# (This would NOT happen if -rcfile magic cmd-line option were used).
+#
+# WARNING: Before 8.1.70, *.mag on cmd-line that was only found in cell search path set by .magicrc inits,
+# would FAIL to determine the default tech-file.
+#
+# rb@ef 2015-06-30 author
+# rb 2020-03-11 embed some library functions, to standalone from efabless-opengalaxy env, test via magic-8.2.194
+#
+# magic itself outputs following usage message though -rcfile doesn't appear to work (in some versions):
+# Usage: magic [-g gPort] [-d devType] [-m monType] [-i tabletPort] [-D] [-F objFile saveFile]
+# [-T technology] [-rcfile startupFile | -norcfile][-noconsole] [-nowindow] [-wrapper] [file]
+#
+set Prog "magicDrc"
+
+set argv [eval "list $env(_M0)"] ;# orig. mix of native plus custom args, for logging all args to script
+
+proc usage {args} {
+ if {[llength $args] > 0} {
+ puts "ERROR: ${::Prog}: [join $args]"
+ }
+ puts {usage: [ -T <techfilePath> ] [-S <drcStyleName>] [-N] [-l FILE_NAME] <magFileName>}
+ puts " -T name specific techfile, passed to magic itself only, overrides tech implied by magFileName"
+ puts " -S if given, changes from techfile's default drc style (perhaps \"drc(fast)\") to named style, for example: -S \"drc(full)\""
+ puts " -l if given, enumerates EVERY individual error bbox to the FILE_NAME"
+ puts " -N if given, do not use -dereference option of load for topcell (not available in older magics)"
+ puts " Stdout will log a pareto of error type by count regardless."
+ puts ""
+ puts " Recommend to run in dir with a ./.magicrc (or ./magic_setup) to configure magic's"
+ puts " cell search path, thru addpath statements, to locate all cells."
+}
+
+# optionally hardcode library proc-s (part of site-wide extensions - always available - in context of efabless/open-galaxy)
+# This is to make the script more standalone from efabless environment; but these capabilities should be native to magic.
+
+if {[info command scratchWritable] == {}} {
+ puts "${::Prog}: hardcoding library proc-s..."
+# Replacement for 'cellname list exists CELLNAME', to fix ambiguity for cell "0".
+# For cell "0" test for membership in 'cellname list allcells'.
+#
+# Instead of returning 0 for (non-existent) and cellname for exists,
+# returns regular 0/1 instead for non-existent/exists.
+#
+# Therefore NOT direct replacement for uses of 'cellname list exists CELL'.
+# Requires code changes.
+proc cellnameExists {cell} {
+ expr {$cell ne "0" && [cellname list exists $cell] eq $cell ||
+ $cell eq "0" && [lsearch -exact [cellname list allcells] $cell] > -1}
+}
+
+#
+# scratchWritable [-cleanup] [cellname1 ...] --
+#
+# Turn readonly cells writable in-memory, via redirect to scratch dir.
+# No cellname args: default is to process just all non-writable cells.
+# Explicit cellname arguments: ARE scatchified EVEN if ALREADY writable.
+# Limitation: Explicit named cell created in-mem, never saved, won't scratchify.
+# If just -cleanup: default is to only do cleanup: don't scratchify
+# any cells.
+#
+# -cleanup: Last scratch-dir, if any, and contents are deleted first.
+# No restoring old filepath of cells, save after cleanup will fail.
+#
+# Caller strongly recommended to first do: 'select top cell; expand'
+# to force whole hier. of a topcell to be loaded from disk into memory.
+#
+# This proc does not force expand cells. Before expanded, cells cannot be
+# checked whether writable, and cannot have filepath changed.
+#
+# For batch DRC, for 'drc listall count', every cell in-memory must
+# appear writable. This is the work-around (caller to 1st ensure
+# hier. is loaded): Reset filepath of readonly cells to a scratch dir,
+# make a dummy/empty .mag in scratch dir for each cell. Change cell's
+# writeable flag.
+#
+# Skipped cells:
+# In all cases, cells are skipped if
+# 'cellname filepath' matches ::scratchWritableDir (already scratchified),
+# This proc does NOT try and force expand; it presumes caller forced an expand
+# thus cells are skipped if:
+# 'cellname filepath' is "default" (can mean not expanded yet, or created never saved),
+# 'cellname filepath' is <CELLNAME>.mag, indicates failed expand (unbound).
+# Note: when filepath gives "default" or <CELLNAME>.mag, the writeable check not meaningful.
+#
+# How to scratchify all in-memory cells (still subject to internal skipping):
+# scratchWritable {*}[cellname list allcells]
+#
+# TODO: use a combo of filepath & flags likely can detect created in-mem,
+# and could redirect those too scratch dir if named explicitly.
+#
+# Side-effects:
+# Runs zero or one subprocess, '/bin/mktemp -d' to make a scratch dir.
+# Redirects where newly modified cells would be saved, if they ever are saved.
+# Make's a scratch dir that needs to be cleaned-up.
+# Leaves empty *.mag files in that scratch dir.
+#
+# Uses/requires proc cellnameExists.
+#
+# Same scratch-dir is reused if called multiple times, until next -cleanup.
+#
+# return value: list of cells not processed (skipped) for reasons cited above.
+# Non-existent cells are also skipped but not included in the return list.
+#
+if {![info exists ::scratchWritableDir]} {set ::scratchWritableDir {}}
+if {![info exists ::scratchWritableVerb]} {set ::scratchWritableVerb 0}
+proc scratchWritable {args} {
+ # parse -cleanup option
+ set clean [expr {[lindex $args 0] eq {-cleanup}}]
+ if {$clean} {
+ set args [lrange $args 1 end]
+ }
+
+ # If explicit cells given: don't limit to processing just readOnly cells.
+ set onlyReadonly [expr {$args == {}}]
+
+ # only if no -cleanup, does empty cell list imply all cells
+ set allcell [cellname list allcells]
+ if {!$clean && $args == {}} {
+ set args $allcell
+ }
+
+ # do cleanup
+ if {$clean} {
+ if {$::scratchWritableDir != {} && [file isdir $::scratchWritableDir]} {
+ set files [glob -dir $::scratchWritableDir -- {*.ext} {*.mag}]
+ lappend files $::scratchWritableDir
+ if {$::scratchWritableVerb} {
+ puts "scratchWritable: running, file delete $files"
+ }
+ eval {file delete} $files
+ set ::scratchWritableDir {}
+ }
+ }
+
+ # Filter out non-existent or unbound cells.
+ # Optionally filter already writable cells.
+ #
+ # Unbounds result from placements of cells that now don't exist:
+ # fail to expand. This proc does not try and force expand; it
+ # presumes a forced expand was already done by caller (if caller
+ # wished).
+ #
+ # Referenced/used cells are initially unexpanded, not yet even located
+ # located in the search path, 'cellname filepath' returns "default".
+ # If expand fails (not found in search path), then 'cellname filepath'
+ # returns <CELLNAME>.mag, if expand worked, the directory containing
+ # the cell.
+ #
+ # If cell was 'cellname create' made, but never saved also "default".
+ # Such a cell is writable. So filter "default" and <CELLNAME>.mag.
+ set skipped {}
+ set ercell1 {}
+ set docells {}
+ foreach cell $args {
+ # filter (without recording as skipped) non-existent cells.
+ if {![cellnameExists $cell]} { continue }
+
+ # filepath = "default": unexpanded (not loaded from disk),
+ # or created in-mem and never saved (is writable already
+ # though flags won't say so): skip both.
+ # TODO: use a combo of filepath & flags likely can detect created in-mem,
+ # and might be able to redirect them too to scratch dir if named explicitly.
+ set tmppath [cellname list filepath $cell]
+ if {$tmppath eq "default"} {
+ lappend skipped $cell
+ continue
+ }
+
+ # flags not meaningful, until expanded or expand attempted.
+ # After expand attempt (filepath != "default"), and flags
+ # can now be used to determine cell unbound: not available.
+ set flags [cellname list flags $cell]
+ if {[lsearch -exact $flags available] < 0} {
+ lappend ercell1 $cell
+ continue
+ }
+
+ if {$onlyReadonly &&
+ [cellname list writeable $cell] eq "writeable"} {
+ lappend skipped $cell
+ continue
+ }
+ lappend docells $cell
+ }
+
+ if {$::scratchWritableVerb} {
+ puts "scratchWritable: skipped cells: $skipped"
+ }
+
+ # don't make a scratch dir if no work to do
+ if {$docells == {}} {
+ if {$::scratchWritableVerb} {
+ puts "scratchWritable: scratch-directed 0 cells"
+ }
+ return $skipped
+ }
+
+ # make a scratch dir if needed
+ if {$::scratchWritableDir == {}} {
+ if {[catch {set dir [string trimright [exec /bin/mktemp -d]]} msg]} {
+ error "ERROR: scratchWritable, '/bin/mktemp -d' failed, $msg"
+ }
+ if {![file isdir $dir] || ![file writable $dir]} {
+ error "ERROR: scratchWritable, mktemp gave $dir, not a writable dir"
+ }
+ set ::scratchWritableDir $dir
+ }
+
+ set ercell2 {}
+ set okcell {}
+ set madef 0
+ foreach cell $docells {
+ # Relocate if needed: filepath doesn't already point to the scratch dir).
+ # 'cellname list filepath <cellNm>' -> appears to omit .mag extension,
+ # but disk-file needs the .mag in the path.
+ set trgr [file join $::scratchWritableDir "$cell"] ;# expected "lookup" path
+ set trgw [file join $::scratchWritableDir "$cell.mag"] ;# true "write" disk path
+ set src [cellname list filepath $cell]
+ if {[cellname list filepath $cell] ne $trgr && [cellname list filepath $cell] ne $trgw} {
+
+ # make empty .mag for the cell
+ if {[catch {set outmag [open $trgw w]} msg]} {
+ lappend ercell2 $cell
+ continue
+ }
+ incr madef
+ close $outmag
+
+ # relocate cell to new file
+ cellname list filepath $cell $::scratchWritableDir
+ }
+
+ # make cell writable
+ cellname list writeable $cell true
+ lappend okcell $cell
+ }
+
+ if {$::scratchWritableVerb} {
+ puts "scratchWritable: scratch-directed $madef cells"
+ }
+ if {$ercell1 != {} || $ercell2 != {}} {
+ set pre "ERROR: scratchWritable, "
+ set msg {}
+ if {$ercell1 != {}} {
+ lappend msg "$pre unbound cell(s): $ercell1"
+ }
+ if {$ercell2 != {}} {
+ lappend msg "$pre failed to make .mag for cell(s): $ercell2"
+ }
+ error [join $msg "\n"]
+ }
+ set skipped
+} ;# end proc scratchWritable
+}
+
+# without top-level proc around bulk of script, intermediate error statements don't abort script.
+proc main {argv} {
+
+# process name-value pair options, if any
+set nbrErr 0
+set ndx 0
+set max [llength $argv]
+set extTechOpt {} ;# -T ...
+set enumFilel {} ;# -l ... enum output file
+set variant {} ;# -S ... non-default drc style
+set flatten 0
+set perfN 0 ;# -P <N> do crude DRC perf. test
+set noderef 0 ;# -N disable dereference option of: 'load ... -dereference'
+
+while {$ndx < $max && [string match "-*" [lindex $argv $ndx]]} {
+ set opt [lindex $argv $ndx]
+ incr ndx
+ switch -exact -- $opt {
+ -T {
+ if {$ndx == $max} {
+ usage "missing tech-file argument for -T option"
+ exit 1
+ }
+ set extTechOpt [lindex $argv $ndx]
+ incr ndx
+ }
+ -S {
+ if {$ndx == $max} {
+ usage "missing drcStyle argument for -S option"
+ exit 1
+ }
+ set variant [lindex $argv $ndx]
+ incr ndx
+ }
+ -P {
+ if {$ndx == $max} {
+ usage "missing count argument for -P option"
+ exit 1
+ }
+ set perfN [lindex $argv $ndx]
+ incr ndx
+ }
+ -F {
+ set flatten 1
+ }
+ -N {
+ set noderef 1
+ }
+ -l {
+ if {$ndx == $max} {
+ usage "missing outputFile argument for -l option"
+ exit 1
+ }
+ set enumFilel [lindex $argv $ndx]
+ incr ndx
+ if {[catch {set enumOut [open $enumFilel w]} msg]} {
+ error "ERROR: ${::Prog}: failed to open-for-write '$enumFilel' threw error, $msg"
+ }
+ puts "${::Prog}: enumerating each error bbox to: $enumFilel"
+ }
+ default {
+ usage "unknown option: $opt"
+ exit 1
+ }
+ }
+}
+
+if {$ndx == $max} {
+ usage "missing magFileName argument, the topcell"
+ exit 1
+}
+
+# get cmd-line topcell, minus dir-path; and minus extension IFF ext is .mag
+set topc [file tail [lindex $argv $ndx]] ; incr ndx
+if {[file extension $topc] eq ".mag"} {
+ set topc [file rootname $topc]
+}
+set topcStr $topc
+
+# abort if user supplies extra args.
+if {$ndx != $max} {
+ usage "extra/unspported arg past magFileName, '[lindex $argv $ndx]'"
+ exit 1
+}
+
+# load the techfile
+if {$extTechOpt != ""} {
+ if {![file readable $extTechOpt]} {
+ error "ERROR: ${::Prog}: tech-file \"$extTechOpt\" is not readable."
+ }
+
+ tech load $extTechOpt
+
+ # Verify the cmd-line -T option (if any) is still the current 'tech filename'. If we didn't
+ # explicitly 'tech load' ourselves, the .magicrc or magic.setup might 'tech load' something else.
+ # The 'file join [pwd] ...' makes relative path absolute, but without resolving
+ # all symlinks (which 'file normalize' would do).
+ set techf2 [file join [pwd] [tech filename]]
+ set techf1 [file join [pwd] $extTechOpt]
+ if {$techf1 != $techf2} {
+ error "ERROR: ${::Prog}: failed tech-load \"$techf1\" (tech-filename=\"$techf2\" not a match)"
+ }
+}
+
+# if mag-cell were passed natively on magic cmd-line, this is too late:
+if {$noderef} {
+ load $topc
+} else {
+ load $topc -dereference
+}
+
+# error checks: ensure (1st) cmd-line cellname now in-memory, and is now the current cell
+
+set topcells [cellname list top]
+# filter (UNNAMED)
+set topcells [lsearch -exact -not -all -inline $topcells "(UNNAMED)"]
+# puts "cellname-list-top is: $topcells"
+
+# could use [cellname list flags $topc] and ensure non-null result (list with available),
+# but if it fails (cell not found), it generates unwanted stdout.
+if {[lsearch -exact [cellname list allcells] $topc] < 0} {
+ error "ERROR: ${::Prog}: cmd-line topcell \"$topc\" not in magic's list of allcells."
+}
+
+if {[lsearch -exact $topcells $topc] < 0} {
+ puts "WARNING: ${::Prog}: cmd-line topcell \"$topc\" not in magic's list of topcells: $topcells"
+}
+
+# crude way even in batch to determine the "current" cell; perhaps not yet the "Edit" cell
+# WARNING, if topcell locked elsewhere or not writable, it can't become the "Edit" cell.
+set topcw [cellname list window]
+if {$topcw ne $topc} {
+ error "ERROR: ${::Prog}: cmd-line topcell, $topc, is not the current cell, 'cellname list window'=$topcw"
+}
+
+# for topcell, filepath==default doesn't change by expand,
+# indicates unknown cell created in-memory by magic's startup sequence.
+if {[cellnameExists $topc] &&
+ [cellname list filepath $topc] eq "default"} {
+ puts "Search path for cells is \"[path search]\""
+ error "ERROR: ${::Prog}: cmd-line topcell, $topc, auto-created in-memory: not found in cell search path"
+}
+
+if {$flatten} {
+ # delete (UNNAMED) if any.
+ set trg "(UNNAMED)"
+ if {[cellnameExists $trg]} {cellname delete $trg}
+
+ # rename top cell to (UNNAMED)
+ cellname rename $topc $trg
+
+ # now Edit Cell contents are original top cell, but under name (UNNAMED)
+ # flatten Edit-Cell into original top cell name
+ puts "${::Prog}: flattening..."
+ flatten $topc
+
+ # load and edit new version of top cell. This is from in-memory, just making it current-cell.
+ # (So with or without -dereference is expected would have discernable effect by now;
+ # and since it's flattened there are no subcell instances either).
+ if {$noderef} {
+ load $topc
+ } else {
+ load $topc -dereference
+ }
+
+ # crude way even in batch to determine the "current" cell; perhaps not yet the "Edit" cell
+ # WARNING, if topcell locked elsewhere or not writable, it can't become the "Edit" cell.
+ set topcw [cellname list window]
+ if {$topcw ne $topc} {
+ error "ERROR: ${::Prog}: assertion failed, post-flatten, $topc, is not the current cell, 'cellname list window'=$topcw"
+ }
+
+ # should not be necessary:
+ select top cell
+ edit
+
+ # crude way even in batch to determine the "current" cell; perhaps not yet the "Edit" cell
+ # WARNING, if topcell locked elsewhere or not writable, it can't become the "Edit" cell.
+ set topcw [cellname list window]
+ if {$topcw ne $topc} {
+ error "ERROR: ${::Prog}: assertion-2 failed, post-flatten, $topc, is not the current cell, 'cellname list window'=$topcw"
+ }
+}
+
+# todo: Need a check for non-existent topcell (though magic reported not-found and auto-created it).
+# todo: We should locate fullpath to topcell on disk to record this in the log.
+#
+# WARNING, magic junkCell, or magic junkDir/junkCell (passing paths to cells that don't exist),
+# generate startup error messages (could not open cell), but magic creates the new cell in memory.
+# No simple way to detect this after the fact. Can walk the cell search path to verify it's on disk.
+# For the non-existent cell, magic also discards the dirpath from the cmd-line arg.
+# If it did exist at that path, magic opens it successfully, despite that dir not in search path.
+# A proper check for implicit create of non-existent cell should account for this effect too.
+
+# write a line with timestamp and all arguments to stdout (log)
+# (magic renames the TCL clock command)
+set clockp clock
+if {[info command $clockp] == {} && [info command orig_clock] != {}} {
+ set clockp orig_clock
+}
+set nowSec [$clockp seconds]
+set timestamp [$clockp format $nowSec -format "%Y-%m-%d.%T.%Z"]
+# Show quoted logged argv here so it's machine readable for replay purposes.
+puts "${::Prog}: timestamp: $timestamp, arguments: $::env(_M0)"
+
+puts "${::Prog}: running drc on topcell: $topcStr"
+puts "${::Prog}: tech-name: [tech name] -version: [tech version] -filename: [tech filename] -lambda [tech lambda]"
+
+# log the cell search path for this run. Emulates format output by plain "path" (but which prints more than one the cell search path).
+puts "Search path for cells is \"[path search]\""
+
+set res {}
+if {$variant != {}} {
+ if {[catch {set res [drc list style $variant]} msg]} {
+ puts "ERROR: ${::Prog}: but CONTINUING, 'drc style $variant' threw error, $msg"
+ }
+} else {
+ if {[catch {set res [drc list style]} msg]} {
+ puts "ERROR: ${::Prog}: but CONTINUING, 'drc list style' threw error, $msg"
+ }
+}
+if {$res != {}} {
+ puts "drc style reports:\n$res"
+}
+
+# just Manhattan is default, turn on euclidean, and log new mode
+drc euclidean on
+drc euclidean
+
+# 1st "select top cell": without it drc-list-count is blank, and error count reduced.
+# May be unnecessary in some cases.
+# WARNING: if topcell locked by another process, default box is NOT set to full top cell without this (as of 8.1.70 or earlier)
+select top cell
+# expand cell cells: scratchify step requires this up front else can't force all cells writable.
+expand
+
+# The expand triggered load of all subcells. Till then allcells may be incomplete.
+set allcells [cellname list allcells]
+# filter (UNNAMED)
+set allcells [lsearch -exact -not -all -inline $allcells "(UNNAMED)"]
+set nbrAllCells [llength $allcells]
+# puts "DEBUG: cellname-list-allcells are: $allcells"
+
+# TODO: do explicit separate unbound check here (don't rely on scratchWritable for this)
+
+# make allcells writable. Can error out:
+# if are unbounds, or couldn't make scratch dir or .mag files.
+set scratch [expr {!$flatten}]
+if {$scratch && [catch {scratchWritable} msg]} {
+ puts stderr "ERROR: ${::Prog}: aborting at scratchWritable due error(s):"
+ error $msg
+}
+
+# Erase all preexisting *.drtcl first. Else when cell transitions from
+# dirty in previous run (leaving *.drtcl), to clean, the old *.drtcl
+# remains.
+# TODO: only delete *.drtcl of cells in 'cellname list allcells'?
+# TODO: move this up, before scratchWritable?
+set files [glob -nocomplain -types {f} -- ./*.drtcl]
+if {$files != {}} {
+ # TODO: detect/report failure details better here?
+ puts "${::Prog}: deleting preexisting *.drtcl"
+ set msg {}
+ set delfail [catch {eval {file delete} $files} msg]
+ set files [glob -nocomplain -types {f} -- ./*.drtcl]
+ if {$delfail || $files != {}} {
+ puts "ERROR: ${::Prog}: failed to clean old ./*.drtcl files. $msg"
+ incr nbrErr
+ }
+}
+
+edit ;# Fails if topcell not writable, should not be not needed post scratchWritable
+
+set outScale [cif scale out]
+
+# "select top cell" and box [view bbox] should be equivalent in
+# placing a box around whole cell extent.
+# The box cmd ALSO prints lambda and micron user-friendly box data,
+# but it prints microns with not enough resolution,
+# (and no option to disable that flawed print out).
+#
+# todo: emulate box output in full, except for higher resolution,
+# here we only scale/print the overall bbox in microns.
+# select top cell ;# paranoid, reset the box to data extents post-expand
+# set bbox [view bbox]
+# set bbs {}
+# foreach oord $bbox {
+# lappend bbs [format "%.3f" [expr {$outScale * $oord}]]
+# }
+# puts "outScale: $outScale, view-bbox: $bbox"
+# puts "Root cell box2: ([lindex $bbs 0] [lindex $bbs 1]), ([lindex $bbs 2] [lindex $bbs 3])"
+
+# shouldn't need:
+# drc on
+
+# Want to use 'drc list count' to tell us which cells have errors, so we can
+# run 'drc listall why' on just those cells to enumerate details (which reruns
+# drc again unfortunately).
+
+# For accurate DRC (as of 8.1.70), specifically 'drc list count', need:
+# all-writable cells, then run: 'drc check' & 'drc catchup'.
+# Now we have all writable cells.
+set timeRepeat 1
+if {$perfN > 0} {
+ set timeRepeat $perfN
+}
+set timeres [time {
+ set drcCheckTime1 [time {drc check}]
+ set drcCheckTime2 [time {drc catchup}] } $timeRepeat]
+
+if {$perfN > 0} {
+ puts "perf: ${perfN}X 'drc check','drc catchup': $timeres"
+ puts "perf: last 'drc check' time: $drcCheckTime1"
+ puts "perf: last 'drc catchup' time: $drcCheckTime2"
+ drc statistics
+ drc rulestats
+}
+
+# todo: this 2nd select was in GDS version, test if needed in mag version:
+# 2nd select top cell needed else error count may be reduced (why? bbox does not change due to DRC)
+select top cell
+set outScale [cif scale out]
+set bbox [view bbox]
+set bbs {}
+foreach oord $bbox {
+ lappend bbs [format "%.3f" [expr {$outScale * $oord}]]
+}
+puts "outScale(ostyle=[cif list ostyle]): $outScale, view-bbox: $bbox"
+puts "Root cell box: ([lindex $bbs 0] [lindex $bbs 1]), ([lindex $bbs 2] [lindex $bbs 3])"
+# print several native bbox representations:
+box
+
+# listall vs list appear same as of 8.1.70 or earlier.
+# warning: celllist order is not stable, not repeatable; run to run on same data.
+# puts "DEBUG: (drc listall count total) is $drcListCountTot"
+set celllist [drc listall count]
+set celllist [lsearch -not -all -inline -index 0 -exact $celllist "(UNNAMED)"]
+# puts "DEBUG: (drc listall count) is [drc listall count]"
+set drcListCountTot [drc list count total]
+set nbrErrCells [llength $celllist]
+
+# TODO: major problem: 'drc listall why' repeated an every cell, will do subcells
+# multiple times, as many times as their depth in the hier.
+
+# canonicalize order of celllist, move topc to last (if present whatsoever).
+# force our own artificial entry for topc (zero errors) if not present (was clean)
+# puts "DEBUG: celllist before: $celllist"
+set topcPair [lsearch -inline -index 0 -exact $celllist $topc]
+set celllist [lsearch -not -all -inline -index 0 -exact $celllist $topc]
+set celllist [lsort -index 0 -dictionary $celllist]
+if {$topcPair == {}} {
+ # puts "DEBUG: $topc clean, forcing celllist entry for it"
+ set topcPair [list $topc 0]
+}
+lappend celllist $topcPair
+# puts "DEBUG: celllist after: $celllist"
+# puts "DEBUG: adjusted celllist(drc list count) is $celllist"
+
+# loop over celllist
+set doFeedback 1 ;# TODO: add cmd-line option to control this
+
+# collect 'dry listall why' for the cells in 'cell list count' with non-zero errors
+# If 'drc listall why' does report zero (shouldn't since we're only processing cells
+# with non-zero counts), it unavoidably writes to console a No drc errors found message.
+# We don't want such polluting our list of per-cell pareto's, so don't risk running
+# drc why in-line, in-between per-cell paretos.
+array set cell2why [list $topc {}] ;# default at least empty topcell why list
+foreach pair $celllist {
+ if {[lindex $pair 1] < 1} {continue} ;# only happens for topcell if topcell clean
+ set acell [lindex $pair 0]
+
+ # TODO: magic needs a useful error checkable load command.
+ # The 'load' writes errors to console/stdout, but never throws an error,
+ # nor gives a useful return value. i.e. These catch never catch.
+ if {$noderef} {
+ if {[catch {set res [load $acell]} msg]} {
+ puts "ERROR: ${::Prog}: 'load $acell' threw error, $msg"
+ exit 1
+ }
+ } else {
+ if {[catch {set res [load $acell -dereference]} msg]} {
+ puts "ERROR: ${::Prog}: 'load $acell -dereference' threw error, $msg"
+ exit 1
+ }
+ }
+ select top cell ;# paranoid, that without it, drc's are reduced
+
+ # optionally do crude DRC perf. analysis here. Only for top-cell, only if -P <N> option given.
+ set timeRepeat 1
+ if {$perfN > 0 && $topc eq $acell} {
+ set timeRepeat $perfN
+ }
+ set timeres [time {set cell2why($acell) [drc listall why]} $timeRepeat]
+ if {$perfN > 0 && $topc eq $acell} {
+ puts "perf: ${::Prog}: for '$acell', ${perfN}X 'drc listall why': $timeres"
+ }
+}
+
+# done with all magic-specifics here. Shouldn't need scratch dir any longer.
+# If this prints something (generally does), don't want it after the pareto table.
+
+# clean/remove the tmp scratch dir and contents
+# TODO: all fatal errors need to call a cleanup proc that includes this before abort
+if {$scratch && [catch {scratchWritable -cleanup} msg]} {
+ puts "ERROR: ${::Prog}: 'scratchWritable -cleanup' threw error, $msg"
+ incr nbrErr
+}
+
+set gtotal 0
+set gcells 0
+foreach pair $celllist {
+ puts ""
+ set acell [lindex $pair 0]
+ if {![info exists cell2why($acell)]} {
+ puts "ERROR: ${::Prog}: cell: $acell, assertion failed, no drc-why list for 'drc list count' pair: $pair"
+ # exit 1
+ continue
+ }
+ set whys $cell2why($acell)
+
+ # enumerate errors under box, plain "drc why" only reports unique types, no quantities
+ # as-yet-undocumented "drc listall why" gives: {errStr1 {errBox1 ...} errStr2 {errBox1 ...} ... }
+ set pareto {}
+ set total 0
+ set enumTotal 0
+ set types 0
+ set typeDup 0
+ set dups 0
+
+ set fbOut {}
+ # file path for feedback, keep in CWD
+ if {$doFeedback && $fbOut == {}} {
+ set fbOut "./$acell.drtcl"
+ if {![file writable $fbOut] &&
+ ([file exists $fbOut] || ![file writable [file dir $fbOut]])} {
+ puts stderr "ERROR: ${::Prog}: feedback output not writable, $fbOut"
+ incr nbrErr
+ set fbOut {}
+ } elseif {[catch {set outfb [open $fbOut w]} msg]} {
+ puts stderr "ERROR: ${::Prog}: failed to truncate previous feedback output, $fbOut : $msg"
+ incr nbrErr
+ set fbOut {}
+ }
+ }
+ foreach {str boxes} $whys {
+ # sort errors
+ set boxes [lsort -dictionary $boxes]
+
+ # for our pareto, gather data
+ set this [llength $boxes]
+ incr total $this
+ incr types
+ lappend pareto [list $this $str]
+
+ # for enumOut, emulate formatting of $CAD_ROOT/magic/tcl/drc.tcl, which is
+ # not tk pure: fails with complaint about winfo
+ # note: we walk these errors also in order to count/report stats on duplicates, even if not outputing enumerations
+ if {[info exists enumOut]} {
+ if {$types == 1} {
+ puts $enumOut "[join $pair]\n----------------------------------------"
+ }
+ puts $enumOut "${str}\n----------------------------------------"
+ }
+ set lastq {}
+ set thisDup 0
+ foreach quad $boxes {
+ set quadUM {}
+ foreach coord $quad {
+ set valum [expr {$coord * $outScale}]
+ set valumf [format "%.3f" $valum]
+ lappend quadUM "${valumf}um"
+ }
+ set dup [expr {$quad == $lastq}]
+ incr thisDup $dup
+ set line $quadUM
+ if {[info exists enumOut]} {
+ if {$dup} {
+ puts $enumOut "[join $line] #dup"
+ } else {
+ puts $enumOut [join $line]
+ }
+ }
+ if {$fbOut != {}} {
+ set line [join $quadUM]
+ regsub -all -- "(\[\[\"\$\\\\])" $str {\\\1} strdq
+ puts $outfb "[concat box $line]" nonewline
+ puts $outfb " ; feedback add \"$strdq\" medium" nonewline
+ if {$dup} {
+ puts $outfb " ;#dup"
+ } else {
+ puts $outfb ""
+ }
+ }
+
+ incr enumTotal
+ set lastq $quad
+ }
+ if {$thisDup} {
+ incr typeDup
+ incr dups $thisDup
+ }
+ if {[info exists enumOut]} {
+ puts $enumOut "----------------------------------------\n"
+ }
+ }
+
+ if {$fbOut != {}} {
+ close $outfb
+ set outfb {}
+ }
+
+ set pareto [lsort -integer -decreasing -index 0 $pareto]
+ if {$total > 0} {
+ puts "--- #err|description, table for cell: $acell"
+ }
+ foreach pair $pareto {
+ puts "[format {%8d} [lindex $pair 0]] [lindex $pair 1]"
+ }
+ if {$typeDup} {
+ puts "[format {%8d} $dups] total duplicate error(s) among $typeDup error type(s), cell: $acell"
+ }
+ puts "[format {%8d} $total] total error(s) among $types error type(s), cell: $acell"
+ # add to grand-totals
+ incr gcells
+ incr gtotal $total
+
+ # always compare the total from the enum to the pareto as error check
+ if {$total != $enumTotal} {
+ puts "ERROR: ${::Prog}: cell: $acell, assertion failed, pareto vs enum count mismatch: $total != $enumTotal"
+ incr nbrErr
+ }
+}
+
+# TODO: in the summary echo also techfile-full-path and drc-style name?
+# grand totals
+puts "[format {%8d} $nbrErrCells] of $nbrAllCells cell(s) report error(s)"
+puts "[format {%8d} $gtotal] grand-total error(s) across $gcells cell(s)"
+
+# wish to compare the drc-list-count-total to the pareto total.
+# Per te 2014-08-27 : it is not an error.
+# if {$total != $drcListCountTot} {
+# puts "info: ${::Prog}: drc-list-count-total vs drc-listall-why mismatch {drc list count total} gave $drcListCountTot, but {drc listall why} gave $total"
+# }
+
+if {[info exists enumOut]} {
+ close $enumOut
+}
+
+# set celllist4 [drc list count]
+# puts "DEBUG: drc list count0: $celllist0"
+# puts "DEBUG: drc list count1: $celllist1"
+# puts "DEBUG: drc list count2: $celllist2"
+# puts "DEBUG: drc list count3: $celllist3"
+# puts "DEBUG: native (drc list count) is $celllistn"
+# puts "DEBUG: drc list count4: $celllist4"
+
+# todo: implement super-pareto, ranked table of SUM of all DRC errs/counts from ALL cells.
+# (It still would not reflect as-if-flat hierarchical expansion due to repetition of instances).
+
+set nbrErr
+}
+
+# non-zero exit-status on errors, either if thrown by main, or counted and returned by main
+set nbrErr 0
+if {[catch {set nbrErr [main $argv]} msg]} {
+ puts stderr $msg
+ set nbrErr 1
+} elseif {$nbrErr > 0} {
+ puts "ERROR: ${::Prog}: script terminated with errors reported above."
+}
+exit $nbrErr
+
+# for emacs syntax-mode:
+# Local Variables:
+# mode:tcl
+# End:
diff --git a/caravel/utils/magicGdrc b/caravel/utils/magicGdrc
new file mode 100644
index 0000000..88280ee
--- /dev/null
+++ b/caravel/utils/magicGdrc
@@ -0,0 +1,911 @@
+#!/bin/sh
+# SPDX-FileCopyrightText: 2014, 2015, 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+# Copyright (C) 2014, 2015, 2020 efabless Corporation. All Rights Reserved.
+# send a very-first -T FILE to magic's startup, hide all other args from magic-startup
+# for-bash\
+ export _M0= ;\
+ for i in "$@" ; do _M0="$_M0${_M0:+ }\"${i//\"/\\\"}\""; done ;\
+ case "$1" in -T) tch="$2"; shift; shift; _MARGS="$*" exec magic -dnull -noconsole -T "$tch" <"$0" ;; esac
+# hide next line from magic(tclsh):\
+_MARGS="$*" exec magic -dnull -noconsole <"$0"
+#
+# magicDRC: run magic-DRC in batch on a GDS file, tabulate/pareto the error counts.
+#
+# rb@ef 2014-08-28 author
+# rb 2020-02-19 embed some library functions, to standalone from efabless-opengalaxy env, test via magic-8.2.188
+#
+# todo: support "-" as GDS file arg, to mean GDS from stdin
+#
+
+set ::Prog "magicGdrc"
+set argv [eval "list $env(_M0)"] ;# orig. mix of native plus custom args, for logging all args to script
+# set argv [split $env(_MARGS)] ;# (currently unused)
+
+proc usage {args} {
+ if {[llength $args] > 0} {
+ puts "ERROR: ${::Prog}: [join $args]"
+ }
+ puts {usage: [ -T techfilePath ] [-S <drcStyleName>] [-I <cifIStyleName>] [-km FILE_NAME] [-l FILE_NAME] [-L FILE_NAME] gdsFileName [topCellName]}
+ puts " -T if given, must be very first"
+ puts " -S if given, changes from techfile's default/1st drc style (perhaps \"drc(fast)\") to named style, for example: -S \"drc(full)\""
+ puts " -I if given, changes from techfile's default/1st cifinput style (perhaps \"vendorimport\" or \"import(exact)\") to named style, for example: -I \"import(magic)\""
+ puts " -path-sub do 'gds path subcell yes' (default:no). Make unique subcell for each path: cut #tiles cost of angles."
+ puts " -poly-sub do 'gds polygon subcell yes' (default:no). Make unique subcell for each polygon: cut #tiles cost of angles."
+# gds polygon subcell [yes|no]
+ puts " -pps Short hand, equivalent to giving both: -path-sub -poly-sub"
+ puts ""
+ puts " Error tabulation: By default (slowest, most detail): Report table of counts-by-errorString for all cells."
+ puts " Stdout logs a pareto of error-type by count unless disabled for some/all cells by below; topcell last."
+ puts " -tt Table of counts-by-errorString for ONLY topcell; and just lumped total error count per subcell."
+ puts " -tc Just lumped error counts per cell including topcell (fastest, least detail)."
+ puts " Cells NOT tabulating count-by-errorString can't appear in other output error files: feedback(*.drtcl), -l, -km."
+ puts " For lumped error counts, overlapped error shapes from unique error-types are merged further reducing count."
+ puts ""
+ puts " cell-type +-- (default) --+-- option -tt --+-- option -tc"
+ puts " subcell | count-by-errorString | lumped-error-count | lumped-error-count"
+ puts " topcell | count-by-errorString | count-by-errorString | lumped-error-count"
+ puts ""
+ puts " -km if given, write to FILE_NAME EVERY individual error bbox (MICRONS) in klayout Marker database(XML) format (suggest *.lyrdb)"
+ puts " -l if given, enumerates EVERY individual error bbox (MICRONS) to FILE_NAME, emulates $::CAD_ROOT/magic/tcl/drc.tcl"
+ puts " -L same as -l above, but outputs bbox-es in LAMBDA coordinates, not microns"
+ puts " -nf Do NOT write *.drtcl per-cell feedback files. Can be source-ed in magic and step thru: feedback find."
+ puts ""
+ puts " NOTES: Without explicit tech-file option: the ./.magicrc or ./magic_setup and ~/.magicrc may load a default tech-file."
+ puts " Therefore the tech-file used CAN depend on whether your CWD is ~/design/<CURRENT_DESIGN>/mag when running this script."
+ puts " Since no *.mag are loaded by this script: the cell search path defined by any init files has no impact."
+ puts " Since about 8.3.68, magic may generate error-type \"See error definition in the subcell\". There typically are"
+ puts " redundancies of errors across the hierarchy anyway (but with tech-file err-strings), this seems another form."
+ puts ""
+ puts "example, just list all styles: by causing an error which provokes usage report:"
+ puts " magicGdrc -T /ef/tech/XFAB/EFXH035B/libs.tech/magic/current/EFXH035B.tech"
+ puts "example, same but run in a ~/design/*/mag/ dir, so techfile set by ./.magicrc (else magic's builtin minimum.tech):"
+ puts " magicGdrc"
+ puts "example, run GDS drc, explicit: tech, cif-istyle, drc-style:"
+ puts " magicGdrc -T /ef/tech/SW/EFS8A/libs.tech/magic/current/EFS8A.tech -I vendorimport -S 'drc(full)' /tmp/mytop.gds mytopcell"
+ puts "example, run GDS drc, default tech & styles, write klayout marker database, no per-cell *.drtcl feedback files:"
+ puts " magicGdrc -km /tmp/mytop.lyrdb -nf /tmp/mytop.gds mytopcell"
+ puts "example, same but make subcells for paths & polygons"
+ puts " magicGdrc -km /tmp/mytop.lyrdb -nf -pps /tmp/mytop.gds mytopcell"
+ puts "example, run GDS drc, no feedback (*.drtcl), only lumped/merged err-count for all cells"
+ puts " magicGdrc -tc /tmp/mytop.gds mytopcell"
+ puts "example, run GDS drc, no feedback (*.drtcl), lumped/merged err-count for subcells, detail errors for topcell"
+ puts " magicGdrc -nf -tt /tmp/mytop.gds mytopcell"
+ puts ""
+
+ reportTechFile
+ reportAllStyles
+ puts ""
+
+ if {[llength $args] > 0} {
+ puts "ERROR: ${::Prog}: [join $args]"
+ }
+}
+proc gdsChk {file} {
+ foreach suffix {"" ".gds" ".gds2" ".strm"} {
+ if {[file readable "${file}${suffix}"]} {return 1}
+ }
+ puts "ERROR: ${::Prog}: Cannot open (as-is or with .gds, .gds2, or .strm) to read GDS-II stream from: $file"
+ exit 1
+}
+
+proc reportTechFile {} {
+ puts "${::Prog}: tech-name: [tech name] -version: [tech version] -filename: [tech filename] -lambda [tech lambda]"
+}
+
+# query currently loaded tech-file for styles the user might need for -I -S options
+# Suggest a bad tech-file if none are found or errors thrown.
+# Used after finding error in -I -S options, and probably should add it to the usage.
+proc reportAllStyles {} {
+ set errs {}
+ if {[catch {set allstyle [cif listall istyle]} msg]} {
+ lappend errs "ERROR: ${::Prog}: bad tech-file? failed to 'cif listall istyle', $msg"
+ } elseif {$allstyle == {}} {
+ lappend errs "ERROR: ${::Prog}: bad tech-file? no cifinput styles found by 'cif listall istyle'"
+ } else {
+ puts "info: ${::Prog}: cifinput styles available: $allstyle"
+ }
+ if {[catch {set allstyle [drc listall style]} msg]} {
+ lappend errs "ERROR: ${::Prog}: bad tech-file? failed to 'drc listall style', $msg"
+ } elseif {$allstyle == {}} {
+ lappend errs "ERROR: ${::Prog}: bad tech-file? no drc styles found by 'drc listall style'"
+ } else {
+ puts "info: ${::Prog}: drc styles available: $allstyle"
+ }
+ if {$errs != {}} {
+
+ }
+ return [llength $errs]
+}
+
+# optionally hardcode library proc-s (part of site-wide extensions - always available - in context of efabless/open-galaxy)
+# This is to make the script more standalone from efabless environment; but these capabilities should be native to magic.
+
+if {[info command unbounds] == {}} {
+ puts "${::Prog}: hardcoding library proc-s..."
+# Replacement for 'cellname list exists CELLNAME', to fix ambiguity for cell "0".
+# For cell "0" test for membership in 'cellname list allcells'.
+#
+# Instead of returning 0 for (non-existent) and cellname for exists,
+# returns regular 0/1 instead for non-existent/exists.
+#
+# Therefore NOT direct replacement for uses of 'cellname list exists CELL'.
+# Requires code changes.
+proc cellnameExists {cell} {
+ expr {$cell ne "0" && [cellname list exists $cell] eq $cell ||
+ $cell eq "0" && [lsearch -exact [cellname list allcells] $cell] > -1}
+}
+
+# Walk allcells to get/return list of cellNames that are unbound.
+# Only use this after: 'select top cell; expand' to expand whole hierarchy.
+#
+# foreach CELL in 'cellname list allcells':
+# if flags says available : it's Bound, goto next cell.
+# if filepath is "default", try to expand the cell.
+# if still "default"**: cell made by "cellname create", never saved, goto next.
+# if filepath is CELL.mag, check for "available" flags, if none: Unbound.
+# else cell is bound.
+# **: should never get there
+proc unbounds {} {
+ set allcells [cellname list allcells]
+ # filter (UNNAMED)
+ set allcells [lsearch -exact -not -all -inline $allcells "(UNNAMED)"]
+ # set nbrAllCells [llength $allcells]
+ set ercell {}
+ foreach cell $allcells {
+ # filter (without recording as skipped) non-existent cells.
+ if {![cellnameExists $cell]} { continue }
+
+ # filepath = "default": unexpanded (not loaded from disk),
+ # or created in-mem and never saved (is writable already
+ # though flags won't say so): skip both.
+ # TODO: use a combo of filepath & flags likely can detect created in-mem
+ set tmppath [cellname list filepath $cell]
+ if {$tmppath eq "default"} {
+ lappend skipped $cell
+ continue
+ }
+
+ # flags not meaningful, until expanded or expand attempted.
+ # After expand attempt (filepath != "default"), and flags
+ # can now be used to determine cell unbound: not available.
+ set flags [cellname list flags $cell]
+ if {[lsearch -exact $flags available] < 0} {
+ lappend ercell $cell
+ continue
+ }
+ }
+ set ercell ;# return list of unbound cells, if any
+}
+}
+
+# without top-level proc around bulk of script, intermediate error statements don't abort script.
+proc main {argv} {
+
+set mlen [llength $argv]
+
+# process name-value pair options, if any
+set nbrErr 0
+set ndx 0
+set max [llength $argv]
+set extTechOpt {} ;# -T ... but not used here
+set enumFilel {} ;# -l ... enum output file
+set enumFileL {} ;# -L ... enum output file
+set enumFileKm {} ;# -km ... enum output file
+set variant {} ;# -S ... non-default drc style
+set istyle {} ;# -I ... non-default cifinput style
+set doFeedback 1 ;# -nf sets to 0: Do not write *.drtcl per-cell feedback files.
+set pathSub 0 ;# -path-sub ... do 'gds path subcell yes'
+set polySub 0 ;# -poly-sub ... do 'gds polygon subcell yes'
+set subcellTab 1 ;# -tt, -tc both turn OFF subcell count-by-error report
+set topcellTab 1 ;# -tc turns OFF topcell count-by-error report
+set flatten 0
+while {$ndx < $max && [string match "-*" [lindex $argv $ndx]]} {
+ set opt [lindex $argv $ndx]
+ incr ndx
+ switch -exact -- $opt {
+ -T {
+ if {$ndx != 1} {
+ usage "-T option must very 1st (here was #$ndx)"
+ exit 1
+ }
+ if {$ndx == $max} {
+ usage "missing tech-file argument for -T option"
+ exit 1
+ }
+ set extTechOpt [lindex $argv $ndx] ;# unused
+ incr ndx
+ }
+ -S {
+ if {$ndx == $max} {
+ usage "missing drcStyle argument for -S option"
+ exit 1
+ }
+ set variant [lindex $argv $ndx]
+ incr ndx
+ }
+ -I {
+ if {$ndx == $max} {
+ usage "missing cifinput-style argument for -I option"
+ exit 1
+ }
+ set istyle [lindex $argv $ndx]
+ incr ndx
+ }
+ -F { set flatten 1}
+ -nf { set doFeedback 0 }
+ -path-sub { set pathSub 1}
+ -poly-sub { set polySub 1}
+ -pps { set pathSub 1; set polySub 1}
+ -tt { set subcellTab 0 ; set topcellTab 1}
+ -tc { set subcellTab 0 ; set topcellTab 0 }
+ -km {
+ if {$ndx == $max} {
+ usage "missing outputFile argument for -km option"
+ exit 1
+ }
+ set enumFileKm [lindex $argv $ndx]
+ incr ndx
+ }
+ -l {
+ if {$ndx == $max} {
+ usage "missing outputFile argument for -l option"
+ exit 1
+ }
+ set enumFilel [lindex $argv $ndx]
+ incr ndx
+ if {[catch {set enumOut [open $enumFilel w]} msg]} {
+ error "ERROR: ${::Prog}: failed to open-for-write '$enumFilel' threw error, $msg"
+ }
+ puts "${::Prog}: enumerating each error bbox to: $enumFilel"
+ }
+ -L {
+ if {$ndx == $max} {
+ usage "missing outputFile argument for -L option"
+ exit 1
+ }
+ set enumFileL [lindex $argv $ndx]
+ incr ndx
+ if {[catch {set enumOutL [open $enumFileL w]} msg]} {
+ error "ERROR: ${::Prog}: failed to open-for-write '$enumFileL' threw error, $msg"
+ }
+ puts "${::Prog}: enumerating each error bbox to: $enumFileL"
+ }
+ default {
+ usage "unknown option: $opt"
+ exit 1
+ }
+ }
+}
+
+if {$ndx == $max} {
+ usage {Insufficient number of arguments, need gdsFileName [topCellName]}
+ exit 1
+}
+
+set gdsf [lindex $argv $ndx] ; incr ndx
+set topc {}
+set topcStr "(AUTO)"
+if {$ndx < $max} {
+ set topc [lindex $argv $ndx] ; incr ndx
+ set topcStr $topc
+}
+# error if extra options (not understood, something is wrong):
+if {$ndx < $max} {
+ error "ERROR: ${::Prog}: after gdsFile=\"$gdsf\", topcell=\"$topc\" found unsupported extra arguments: [lrange $argv $ndx end]"
+}
+# ndx no longer used for argv position from here
+
+gdsChk $gdsf
+
+# warning on combo of -tc & -km. If -km ok, open its output file.
+if {$enumFileKm ne {}} {
+ if {! $topcellTab} {
+ puts "WARNING: ${::Prog}: with -tc cannot (-km) write klayout-marker-db"
+ } else {
+ if {[catch {set enumOutKm [open $enumFileKm w]} msg]} {
+ error "ERROR: ${::Prog}: failed to open-for-write '$enumFileKm' threw error, $msg"
+ }
+ puts "${::Prog}: enumerating each error bbox to: $enumFileKm"
+ }
+}
+
+# write a line with timestamp and all arguments to stdout (log)
+# (magic renames the TCL clock command)
+set clockp clock
+if {[info command $clockp] == {} && [info command orig_clock] != {}} {
+ set clockp orig_clock
+}
+set nowSec [$clockp seconds]
+set timestamp [$clockp format $nowSec -format "%Y-%m-%d.%T.%Z"]
+# TODO: quote logged argv here as needed so it's machine readable for replay purposes.
+puts "${::Prog}: timestamp: $timestamp, arguments: $argv"
+
+# just Manhattan is default, turn on euclidean, and log new mode
+drc euclidean on
+drc euclidean
+
+# 8.1.83 this worked:
+# drc off; gds drccheck no; gds read ... ; load topcell; select top cell; expand; drc check; drc update; drc listall count
+# By 8.2.64, that fails, the 'drc listall count' reports errors only in the top-cell, no subcells.
+# 8.1.83 & 8.2.193 this works (gds drccheck defaults to on anyway):
+# drc off; gds drccheck yes; gds read ... ; load topcell; select top cell; expand; drc check; drc update; drc listall count
+#
+# But are we properly avoiding redundant drc runs?
+#
+# turn off background checker. We'll invoke checks explicitly.
+drc off
+gds drccheck yes
+puts "drc status (whether background checking enabled) is: [drc status]"
+puts "gds drccheck (whether gds-read marks new cells as need-drc) is: [gds drccheck]"
+
+# set user's drc style; set user's cifinput istyle
+# These are back-to-back without intervening status messages.
+# If both wrong their errors are back-to-back.
+set res {}
+set res [drc list style]
+if {$variant != {}} {
+ set allstyle [drc listall style]
+ set ndx [lsearch -exact $allstyle $variant]
+ if {$ndx < 0} {
+ puts "ERROR: ${::Prog}: drc style '$variant' not one of those available: $allstyle"
+ incr nbrErr
+ } else {
+ set res [drc list style $variant]
+ }
+}
+set res2 [cif list istyle]
+if {$istyle != {}} {
+ set allstyle [cif listall istyle]
+ set ndx [lsearch -exact $allstyle $istyle]
+ if {$ndx < 0} {
+ puts "ERROR: ${::Prog}: istyle '$istyle' not one of those available: $allstyle"
+ incr nbrErr
+ } else {
+ set res2 [cif istyle $istyle]
+ }
+}
+if {$res != {}} {
+ puts "drc style reports:\n$res"
+}
+if {$res2 != {}} {
+ puts "cif istyle reports:\n$res2"
+}
+
+# gds {path,polygon} subcell yes
+if {$pathSub != 0} { gds path subcells yes }
+puts "gds path subcells: [gds path subcells]"
+if {$polySub != 0} { gds polygon subcells yes }
+puts "gds polygon subcells: [gds polygon subcells]"
+
+# todo: this catch never happens. Need nicer error check of 'gds read' somehow. Can check for zero-sized file?
+# if use /dev/null for example, it prints its own error message, but no throw, no useful return value.
+puts "doing: gds read $gdsf ..."
+if {[catch {set res [gds read $gdsf]} msg]} {
+ puts "ERROR: ${::Prog}: 'gds read $gdsf' threw error, $msg"
+ incr nbrErr
+}
+# nothing useful:
+# puts "gds-read res: $res"
+
+set topcells [cellname list top]
+set allcells [cellname list allcells]
+# puts "cellname-list-top from GDS is: $topcells"
+# puts "cellname-list-allcells from GDS are: $allcells"
+# filter (UNNAMED)
+set topcells [lsearch -exact -not -all -inline $topcells "(UNNAMED)"]
+set allcells [lsearch -exact -not -all -inline $allcells "(UNNAMED)"]
+set nbrAllCells [llength $allcells]
+
+if {$topcells == {}} {
+ puts "ERROR: ${::Prog}: GDS-read did not report any useful cell name(s) found."
+ incr nbrErr
+}
+
+if {$nbrErr > 0} {
+ return $nbrErr ;# outside of main, we print termination with errors message
+}
+
+if {$topc == {}} {
+ # try and infer topcell from cellname-list-top.
+ # presume its list of cells not placed anywhere else.
+ # todo: test with "library" GDS having more than one topcell
+ # here we just take the last entry
+ set topc [lindex $topcells end]
+ set topcStr $topc
+ puts "WARNING: auto-picked top-cell \"$topc\"; the topcells inferred from GDS are: $topcells"
+} else {
+ # verify input topc argument exists in GDS read result
+ set ndx [lsearch -exact $allcells $topc]
+ if {$ndx < 0} {
+ puts "ERROR: ${::Prog}: top-cell name: $topc, not found in GDS"
+ puts "info: top cells inferred from GDS are: $topcells"
+ puts "info: all cells inferred from GDS are: $allcells"
+ return [incr nbrErr] ;# outside of main, we print termination with errors message
+ }
+}
+
+puts "${::Prog}: running drc on -gds: $gdsf -topcell: $topcStr"
+reportTechFile
+
+# todo: need to error check load command somehow (no useful return value).
+# it can fail with error message (in log) like:
+# File dne.mag couldn't be found
+# Creating new cell
+if {[catch {set res [load $topc]} msg]} {
+ puts "ERROR: ${::Prog}: 'load $topc' threw error (maybe cellName not found in GDS?), $msg"
+ return [incr nbrErr] ;# outside of main, we print termination with errors message
+}
+# nothing useful:
+# puts "load $topc res: $res"
+
+if {$flatten} {
+ # delete (UNNAMED) if any.
+ set trg "(UNNAMED)"
+ if {[cellnameExists $trg]} {cellname delete $trg}
+
+ # rename top cell to (UNNAMED)
+ cellname rename $topc $trg
+
+ # now Edit Cell contents are original top cell, but under name (UNNAMED)
+ # flatten Edit-Cell into original top cell name
+ puts "${::Prog}: flattening..."
+ flatten $topc
+
+ # load and edit new version of top cell
+ load $topc
+
+ # crude way even in batch to determine the "current" cell; perhaps not yet the "Edit" cell
+ # WARNING, if topcell locked elsewhere or not writable, it can't become the "Edit" cell.
+ set topcw [cellname list window]
+ if {$topcw ne $topc} {
+ puts "ERROR: ${::Prog}: assertion failed, post-flatten, $topc, is not the current cell, 'cellname list window'=$topcw"
+ return [incr nbrErr] ;# outside of main, we print termination with errors message
+ }
+
+ # should not be necessary:
+ select top cell
+ edit
+
+ # crude way even in batch to determine the "current" cell; perhaps not yet the "Edit" cell
+ # WARNING, if topcell locked elsewhere or not writable, it can't become the "Edit" cell.
+ set topcw [cellname list window]
+ if {$topcw ne $topc} {
+ puts "ERROR: ${::Prog}: assertion-2 failed, post-flatten, $topc, is not the current cell, 'cellname list window'=$topcw"
+ return [incr nbrErr] ;# outside of main, we print termination with errors message
+ }
+}
+
+# Erase all preexisting *.drtcl first. Else when cell transitions from
+# dirty in previous run (leaving *.drtcl), to clean, the old *.drtcl
+# remains.
+# TODO: only delete *.drtcl of cells in 'cellname list allcells'?
+if {$doFeedback} {
+ set files [glob -nocomplain -types {f} -- ./*.drtcl]
+ if {$flatten} {
+ # only delete topcell's .drtcl in flatten mode, if there is one
+ set files [lsearch -all -inline -exact $files ./$topc.drtcl]
+ }
+ if {$files != {}} {
+ # TODO: detect/report failure details better here?
+ puts "${::Prog}: deleting preexisting *.drtcl"
+ set msg {}
+ set delfail [catch {eval {file delete} $files} msg]
+ set files [glob -nocomplain -types {f} -- ./*.drtcl]
+ if {$delfail || $files != {}} {
+ puts "ERROR: ${::Prog}: failed to clean old ./*.drtcl files. $msg"
+ incr nbrErr
+ }
+ }
+}
+
+# 1st "select top cell": without it drc-list-count is blank, and error count reduced.
+select top cell
+
+set bbox0 [view bbox]
+set outScale [cif scale out]
+
+# set bbox1 [view bbox]
+
+# "select top cell" and box [view bbox] should be equivalent in
+# placing a box around whole cell extent.
+# The box cmd ALSO prints lambda and micron user-friendly box data,
+# but it prints microns with not enough resolution,
+# (and no option to disable that flawed print out).
+#
+# todo: emulate box output in full, except for higher resolution,
+# here we only scale/print the overall bbox in microns.
+set bbs {}
+foreach oord $bbox0 {
+ lappend bbs [format "%.3f" [expr {$outScale * $oord}]]
+}
+puts "info: outScale: [format "%.6f" $outScale], view-bbox: $bbox0"
+puts "info: Root cell box: ([lindex $bbs 0] [lindex $bbs 1]), ([lindex $bbs 2] [lindex $bbs 3])"
+
+drc check
+drc catchup
+drc statistics
+drc rulestats
+# puts "doing plain: drc count"
+drc count
+
+# 2nd select top cell needed else error count may be reduced (why? bbox does not change due to DRC)
+select top cell
+
+set celllist [drc listall count]
+set drcListCountTot [drc list count total]
+# puts stdout "(drc listall count) is << " nonewline; puts stdout [list $celllist] nonewline; puts " >>"
+# puts stdout "(drc list count) is << " nonewline; puts stdout [list [drc list count]] nonewline; puts " >>"
+# puts stdout "(drc list count total) is << " nonewline; puts stdout [list $drcListCountTot] nonewline; puts " >>"
+# puts stdout "(drc listall count total) is << " nonewline; puts stdout [list [drc listall count total]] nonewline; puts " >>"
+# puts stdout "(drc list why) is << " nonewline; puts stdout [list [drc list why]] nonewline; puts " >>"
+# puts stdout "(drc listall why) is << " nonewline; puts stdout [list [drc listall why]] nonewline; puts " >>"
+
+set bbox2 [view bbox]
+if {$bbox2 != $bbox0} {
+ set bbs {}
+ foreach oord $bbox2 {
+ lappend bbs [format "%.3f" [expr {$outScale * $oord}]]
+ }
+ puts "info: outScale: [format "%.6f" $outScale], view-bbox: $bbox2"
+ puts "info: Root cell box2: ([lindex $bbs 0] [lindex $bbs 1]), ([lindex $bbs 2] [lindex $bbs 3])"
+}
+
+
+# canonicalize order of celllist, move topc to last (if present whatsoever).
+# force our own artificial entry for topc (zero errors) if not present (was clean)
+# puts "celllist before: $celllist"
+set nbrErrCells [llength $celllist]
+set topcPair [lsearch -inline -index 0 -exact $celllist $topc]
+set celllist [lsearch -not -all -inline -index 0 -exact $celllist $topc]
+set celllist [lsort -index 0 -dictionary $celllist]
+if {$topcPair == {}} {
+ # puts "info: ${::Prog}: $topc clean, forcing celllist entry for it"
+ set topcPair [list $topc 0]
+}
+lappend celllist $topcPair
+# puts stdout "adjusted celllist(drc list count) is << " nonewline; puts stdout $celllist nonewline; puts " >>"
+
+array set kmErr2catNm {}
+array set kmErr2catDesc {}
+array set kmCell2item {}
+if {$celllist != {} && [info exists enumOutKm]} {
+ # Header example of .lyrdb klayout Marker format
+ # <?xml version="1.0" encoding="utf-8"?>
+ # <report-database>
+ # <description>Diff of 'x.gds, Cell RINGO' vs. 'x.gds[1], Cell INV2'</description>
+ # <original-file/>
+ # <generator/>
+ # <top-cell>RINGO</top-cell>
+ # <tags>
+ # <tag>
+ # <name>red</name>
+ # <description>Red flag</description>
+ # </tag>
+ # ...
+ # </tags>
+
+ puts $enumOutKm {<?xml version="1.0" encoding="utf-8"?><report-database>}
+ puts $enumOutKm "<description>$topc DRC timestamp: $timestamp, arguments: $argv</description>"
+ puts $enumOutKm {<original-file/><generator/>}
+ puts $enumOutKm "<top-cell>$topc</top-cell>"
+ puts $enumOutKm {<tags/>}
+ puts $enumOutKm {<cells>}
+
+ # multiple <cells>...</cells> sections do accumulate, but cells and categories need
+ # to be defined before use in an item (specific error), and we know cell names here,
+ # so declare all cells to klayout here.
+ #
+ # Cell-specific header of klayout marker file
+ # <cell>
+ # <name>CELLNAME1</name>
+ # <variant>1</variant> (don't need)
+ # </cell>
+ #
+ foreach pair $celllist {
+ set acell [lindex $pair 0]
+
+ # for -tt, no subcell error-detail: don't write subcells in <cells>...</cells> section.
+ if {$acell ne $topc && ! $subcellTab} { continue }
+
+ puts $enumOutKm " <cell><name>$acell</name></cell>"
+ set kmCell2item($acell) {}
+ }
+ puts $enumOutKm {</cells>}
+}
+
+# loop over celllist
+set gtotal 0
+set gcells 0
+set lumpedHeader 0
+foreach pair $celllist {
+ set acell [lindex $pair 0]
+ set acount [lindex $pair 1]
+
+ if {$acell ne $topc && ! $subcellTab} {
+ if {! $lumpedHeader} {
+ puts "--- #err|cell, lumped total counts"
+ set lumpedHeader 1
+ }
+ puts "[format {%8d} $acount] $acell"
+ incr gcells
+ incr gtotal $acount
+ continue
+ }
+ if {$acell eq $topc && ! $topcellTab} {
+ if {! $lumpedHeader} {
+ puts "--- #err|cell, lumped total counts"
+ set lumpedHeader 1
+ }
+ puts "[format {%8d} $acount] $acell"
+ incr gcells
+ incr gtotal $acount
+ continue
+ }
+ puts ""
+
+ # todo: need useful error check of load command
+ if {[catch {set res [load $acell]} msg]} {
+ puts "ERROR: ${::Prog}: 'load $acell' threw error, $msg"
+ return [incr nbrErr] ;# outside of main, we print termination with errors message
+ }
+
+ # instead use quiet version for per-cell selects
+ select top cell
+
+ set drcListCountTot [drc listall count total]
+
+ # enumerate errors under box, plain "drc why" only reports unique types, no quantities
+ # as-yet-undocumented "drc listall why" will give: {errStr1 {errBox1 ...} errStr2 {errBox1 ...} ... }
+ set pareto {}
+ set total 0
+ set enumTotal 0
+ set types 0
+ set typeDup 0
+ set dups 0
+
+ set fbOut {}
+ if {$acount != 0} {
+ # file path for feedback, keep in CWD
+ if {$doFeedback && $fbOut == {}} {
+ set fbOut "./$acell.drtcl"
+ if {![file writable $fbOut] &&
+ ([file exists $fbOut] || ![file writable [file dir $fbOut]])} {
+ puts stderr "ERROR: ${::Prog}: feedback output not writable, $fbOut"
+ incr nbrErr
+ set fbOut {}
+ } elseif {[catch {set outfb [open $fbOut w]} msg]} {
+ puts stderr "ERROR: ${::Prog}: failed to truncate previous feedback output, $fbOut : $msg"
+ incr nbrErr
+ set fbOut {}
+ }
+ }
+
+ foreach {str boxes} [drc listall why] {
+ # sort errors
+ set boxes [lsort -dictionary $boxes]
+ # for our pareto, gather data
+ set this [llength $boxes]
+ incr total $this
+ incr types
+ lappend pareto [list $this $str]
+
+ # for enumOut, emulate formatting of $CAD_ROOT/magic/tcl/drc.tcl, which is
+ # not tk pure: fails with complaint about winfo
+ # note: we walk these errors also in order to count/report stats on duplicates, even if not outputing enumerations
+ if {[info exists enumOut]} {
+ if {$types == 1} {
+ puts $enumOut "[join $pair]\n----------------------------------------"
+ }
+ puts $enumOut "${str}\n----------------------------------------"
+ }
+ if {[info exists enumOutL]} {
+ if {$types == 1} {
+ puts $enumOutL "[join $pair]\n----------------------------------------"
+ }
+ puts $enumOutL "${str}\n----------------------------------------"
+ }
+ if {[info exists enumOutKm]} {
+ # category names must be declared all together up front before use in items
+ # so we only store their names (error strings) and error detail (items)
+ # to dump after all cells and errors are processed.
+ # TODO: Only quote catName in item if embeds dot, instead of full-time
+ # TODO: test klayout handles literal (non-entity) single-quote in double-quoted name
+ set strKmNm $str
+ set strKmDesc $str
+ regsub -all -- {&} $strKmDesc {\&} strKmDesc ;# perhaps not needed; just in case
+ regsub -all -- {<} $strKmDesc {\<} strKmDesc ;# description does not have such bug, so use correct entity
+ regsub -all -- {>} $strKmDesc {\>} strKmDesc ;# perhaps not needed; just in case
+ regsub -all -- {&} $strKmNm {-and-} strKmNm ;# perhaps not needed; just in case
+ regsub -all -- {>} $strKmNm {-gt-} strKmNm ;# perhaps not needed; just in case
+ regsub -all -- {<} $strKmNm {-lt-} strKmNm ;# catName klayout bug: info win truncates at '<' as < entity
+ regsub -all -- "\"" $strKmNm {'} strKmNm ;# we dqoute each catNm in item, so change embedded double to single
+ set kmErr2catNm($str) $strKmNm
+ set kmErr2catDesc($str) $strKmDesc
+ #
+ # example klayout Marker format, header of one item (one error instance)
+ # <item>
+ # <tags/> (don't need?)
+ # <image/> (don't need?)
+ # <category>'DRC-MSG-STR'</category> (cat1.cat2 path delimit by dot: names with dot need single|double quotes)
+ # <cell>RINGO:1</cell> (don't need :N variant suffix)
+ # <visited>false</visited> (optional? start with false?)
+ # <multiplicity>1</multiplicity> (not boolean, if error "represents" more that are NOT enumerated)
+ # <values> ... </values>
+ # </item>
+
+ set itemStr "<item><category>\"$strKmNm\"</category><cell>$acell</cell><values>"
+ }
+ set lastq {}
+ set thisDup 0
+ foreach quad $boxes {
+ set quadUM {}
+ set kmBoxUM {}
+ foreach coord $quad {
+ set valum [expr {$coord * $outScale}]
+ set valumf [format "%.3f" $valum]
+ lappend quadUM "${valumf}um"
+ lappend kmBoxUM ${valumf}
+ }
+ set dup [expr {$quad == $lastq}]
+ incr thisDup $dup
+ set line $quadUM
+ if {[info exists enumOut]} {
+ if {$dup} {
+ puts $enumOut "[join $line] #dup"
+ } else {
+ puts $enumOut [join $line]
+ }
+ }
+ if {[info exists enumOutL]} {
+ if {$dup} {
+ puts $enumOutL "$quad #dup"
+ } else {
+ puts $enumOutL $quad
+ }
+ }
+ if {[info exists enumOutKm]} {
+ # <value>text: 'item: polygon'</value> (text is optional? Repeat the box coordinates here in um?)
+ # <value>polygon: (1.4,1.8;-1.4,1.8;-1.4,3.8;1.4,3.8)</value>
+ # <value>box: (1.4,1.8;-1.4,3.8)</value>
+ # </values>
+ set kmItem $itemStr
+ append kmItem " <value>box: ([lindex $kmBoxUM 0],[lindex $kmBoxUM 1];[lindex $kmBoxUM 2],[lindex $kmBoxUM 3])</value>"
+ if {$dup} {
+ append kmItem " <value>text: 'dup'</value>"
+ }
+ append kmItem " </values></item>"
+ lappend kmCell2item($acell) $kmItem
+ }
+ if {$fbOut != {}} {
+ set line [join $quadUM]
+ regsub -all -- "(\[\[\"\$\\\\])" $str {\\\1} strdq
+ puts $outfb "[concat box $line]" nonewline
+ puts $outfb " ; feedback add \"$strdq\" medium" nonewline
+ if {$dup} {
+ puts $outfb " ;#dup"
+ } else {
+ puts $outfb ""
+ }
+ }
+
+ incr enumTotal
+ set lastq $quad
+ }
+ if {$thisDup} {
+ incr typeDup
+ incr dups $thisDup
+ }
+ if {[info exists enumOut]} {
+ puts $enumOut "----------------------------------------\n"
+ }
+ if {[info exists enumOutL]} {
+ puts $enumOutL "----------------------------------------\n"
+ }
+ }
+ }
+
+ if {$fbOut != {}} {
+ close $outfb
+ set outfb {}
+ }
+
+ set pareto [lsort -integer -decreasing -index 0 $pareto]
+ if {$total > 0} {
+ puts "--- #err|description, table for cell: $acell"
+ }
+ foreach pair $pareto {
+ puts "[format {%8d} [lindex $pair 0]] [lindex $pair 1]"
+ }
+ if {$typeDup} {
+ puts "[format {%8d} $dups] total duplicate error(s) among $typeDup error type(s), cell: $acell"
+ }
+ puts "[format {%8d} $total] total error(s) among $types error type(s), cell: $acell"
+ # add to grand-totals
+ incr gcells
+ incr gtotal $total
+
+ # always compare the total from the enum to the pareto as error check
+ if {$total != $enumTotal} {
+ puts "ERROR: ${::Prog}: cell: $acell, internal error, pareto vs enum count mismatch: $total != $enumTotal"
+ incr nbrErr
+ }
+ # wish to compare the drc-list-count-total to the pareto total.
+ # Per te 2014-08-27 : it is not an error.
+ if {$total != $drcListCountTot} {
+ # puts "info: ${::Prog}: cell: $acell, drc-list-count-total vs drc-listall-why mismatch {drc list count total} gave $drcListCountTot, but {drc listall why} gave $total"
+ }
+}
+
+# grand totals
+puts "[format {%8d} $nbrErrCells] of $nbrAllCells cell(s) report error(s)"
+puts "[format {%8d} $gtotal] grand-total error(s) across $gcells cell(s)"
+
+if {[info exists enumOut]} {
+ close $enumOut
+}
+if {[info exists enumOutL]} {
+ close $enumOutL
+}
+if {[info exists enumOutKm]} {
+ # declare all category names and descriptions, note '<' in name vs description are represented differently
+ #
+ # <categories><category><name>layerN width -lt- 1.0um</name>
+ # <description>layerN width < 1.0um</description></category>
+ # <category> ... </category></categories>
+ #
+ puts $enumOutKm "<categories>"
+ foreach errStr [array names kmErr2catNm] {
+ set nm $kmErr2catNm($errStr)
+ set desc $kmErr2catDesc($errStr)
+ puts $enumOutKm " <category><name>$nm</name><description>$desc</description></category>"
+ }
+ puts $enumOutKm "</categories>"
+
+ # dump all items (after all cells and all categories have been defined up front)
+ puts $enumOutKm "<items>"
+ foreach {acell items} [array get kmCell2item] {
+ foreach item $items {
+ puts $enumOutKm $item
+ }
+ }
+ puts $enumOutKm "</items>"
+
+ # footer example .lyrdb klayout Marker file
+ # </report-database>
+ puts $enumOutKm {</report-database>}
+ close $enumOutKm
+}
+# todo: implement super-pareto, ranked table of SUM of all DRC errs/counts from ALL cells.
+# (It still would not reflect as-if-flat hierarchical expansion due to repetition of instances).
+
+set nbrErr ;# return value
+} ;# end main
+
+# non-zero exit-status on errors, either if thrown by main, or counted and returned by main
+set nbrErr 0
+if {[catch {set nbrErr [main $argv]} msg]} {
+ puts stderr $msg
+ set nbrErr 1
+} elseif {$nbrErr > 0} {
+ puts "ERROR: ${::Prog}: script terminated with errors reported above."
+}
+exit $nbrErr
+
+# for emacs syntax-mode:
+# Local Variables:
+# mode:tcl
+# End:
diff --git a/caravel/utils/parse_klayout_xor_log.py b/caravel/utils/parse_klayout_xor_log.py
new file mode 100644
index 0000000..d93fb2c
--- /dev/null
+++ b/caravel/utils/parse_klayout_xor_log.py
@@ -0,0 +1,43 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+import argparse
+import re
+
+parser = argparse.ArgumentParser(
+ description='extracts the total xor differnces from an xor log')
+
+parser.add_argument('--log_file', '-l',required=True,
+ help='log file')
+
+parser.add_argument('--output', '-o', required=True,
+ help='output file to store results')
+
+args = parser.parse_args()
+log_file_name = args.log_file
+out_file_name = args.output
+
+string = "XOR differences:"
+pattern = re.compile(r'\s*%s\s*([\d+]+)' % string)
+tot_cnt = 0
+with open(log_file_name, "r") as f:
+ for line in f:
+ m = pattern.match(line)
+ if m:
+ tot_cnt += int(m.group(1))
+
+outFileOpener = open(out_file_name, "w")
+outFileOpener.write("Total XOR differences = "+ str(tot_cnt))
+outFileOpener.close()
diff --git a/caravel/utils/scrotLayout.py b/caravel/utils/scrotLayout.py
new file mode 100644
index 0000000..6eb282e
--- /dev/null
+++ b/caravel/utils/scrotLayout.py
@@ -0,0 +1,59 @@
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+import pya
+import re
+import os
+
+WIDTH = 2048
+HEIGHT = 2048
+
+app = pya.Application.instance()
+win = app.main_window()
+
+# Load technology file
+print('[INFO] Reading tech file: ' + str(tech_file))
+tech = pya.Technology()
+tech.load(tech_file)
+
+layoutOptions = tech.load_layout_options
+
+# Load def file in the main window
+print('[INFO] Reading Layout file: ' + str(input_layout))
+cell_view = win.load_layout(input_layout, layoutOptions, 0)
+layout_view = cell_view.view()
+
+layout_view.load_layer_props(os.path.splitext(tech_file)[0]+'.lyp')
+
+layout_view.max_hier()
+# layout_view.clear_layers()
+
+# Hide layers with these purposes
+hidden_purposes = [0, 4, 5]
+
+li = layout_view.begin_layers()
+while not li.at_end():
+ lp = li.current()
+ if lp.source_datatype in hidden_purposes:
+ new_lp = lp.dup()
+ new_lp.visible = False
+ layout_view.set_layer_properties(li, new_lp)
+
+ li.next()
+
+print("[INFO] Writing out PNG screenshot '{0}'".format(input_layout+".png"))
+layout_view.save_image(input_layout+".png", WIDTH, HEIGHT)
+print("Done")
+app.exit(0)
diff --git a/caravel/utils/scrotLayout.sh b/caravel/utils/scrotLayout.sh
new file mode 100644
index 0000000..3b81a3f
--- /dev/null
+++ b/caravel/utils/scrotLayout.sh
@@ -0,0 +1,32 @@
+#!/bin/sh
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+set -e
+
+: ${1?"Usage: $0 tech_file input"}
+: ${2?"Usage: $0 tech_file input"}
+
+echo "Using Techfile: $1"
+echo "Using layout file: $2"
+
+# The -a here is necessary to handle race conditions.
+# This limits the max number of possible jobs to 100.
+xvfb-run -a klayout -z \
+ -rd input_layout=$2 \
+ -rd tech_file=$1 \
+ -rm $(dirname $0)/scrotLayout.py
+
+exit 0
diff --git a/caravel/utils/xor.drc b/caravel/utils/xor.drc
new file mode 100644
index 0000000..6caee91
--- /dev/null
+++ b/caravel/utils/xor.drc
@@ -0,0 +1,42 @@
+# A general XOR script
+# (https://www.klayout.de/forum/discussion/100/xor-vs-diff-tool)
+# This script uses KLayout's DRC language to implement a generic
+# XOR between two layouts. The name of the layouts is given
+# in $a and $b.
+
+# For layout-to-layout XOR with multiple cores, run this script with
+# ./klayout -r xor.drc -rd thr=NUM_CORES -rd top_cell=TOP_CELL_NAME -rd a=a.gds -rd b=b.gds -rd ol=xor.gds -zz
+# (replace NUM_CORES by the desired number of cores to utilize
+
+# enable timing output
+verbose
+
+# set up input a
+a = source($a, $top_cell)
+
+# set up input b
+b = source($b, $top_cell)
+
+$o && $ext != "gds" && report("XOR #{$a} vs. #{$b}", $o)
+$ol && $ext == "gds" && target($ol, $co || "XOR")
+
+$thr && threads($thr) || threads(2)
+
+# collect all common layers
+layers = {}
+[ a.layout, b.layout ].each do |ly|
+ ly.layer_indices.each do |li|
+ i = ly.get_info(li)
+ layers[i.to_s] = i
+ end
+end
+
+# perform the XOR's
+layers.keys.sort.each do |l|
+ i = layers[l]
+ info("--- Running XOR for #{l} ---")
+ x = a.input(l) ^ b.input(l)
+ info("XOR differences: #{x.data.size}")
+ $o && $ext != "gds" && x.output(l, "XOR results for layer #{l} #{i.name}")
+ $ol && $ext == "gds" && x.output(i.layer, i.datatype, i.name)
+end
diff --git a/caravel/utils/xor.sh b/caravel/utils/xor.sh
new file mode 100644
index 0000000..44800d6
--- /dev/null
+++ b/caravel/utils/xor.sh
@@ -0,0 +1,36 @@
+#!/bin/sh
+# SPDX-FileCopyrightText: 2020 Efabless Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# SPDX-License-Identifier: Apache-2.0
+
+: ${1?"Usage: $0 file1.gds file2.gds <top_level_module_name> output.gds|markers.xml"}
+: ${2?"Usage: $0 file1.gds file2.gds <top_level_module_name> output.gds|markers.xml"}
+: ${3?"Usage: $0 file1.gds file2.gds <top_level_module_name> output.gds|markers.xml"}
+: ${4?"Usage: $0 file1.gds file2.gds <top_level_module_name> output.gds|markers.xml"}
+
+
+echo "First Layout: $1"
+echo "Second Layout: $2"
+echo "Design Name: $3"
+echo "Output GDS will be: $4"
+
+xvfb-run -a klayout -r $(dirname $0)/xor.drc \
+ -rd top_cell=$3 \
+ -rd a=$1 \
+ -rd b=$2 \
+ -rd thr=$(nproc) \
+ -rd ol=$4 \
+ -rd o=$4 \
+ -rd ext=${4##*.} \
+ -zz