A method includes bonding a first wafer to a second wafer, with a first plurality of dielectric layers in the first wafer and a second plurality of dielectric layers in the second wafer bonded between a first substrate of the first wafer and a second substrate in the second wafer. A first opening is formed in the first substrate, and the first plurality of dielectric layers and the second wafer are etched through the first opening to form a second opening. A metal pad in the second plurality of dielectric layers is exposed to the second opening. A conductive plug is formed extending into the first and the second openings.