If you file bankruptcy you will keep your home; unless you want to surrender it to the bank.
In order to keep your home you will need to at a minimum be able to make the current monthly payment on the first mortgage.
If you are filing chapter 7 bankruptcy, you will need to be current with all mortgages on the home when you file and continue to be current after the case is over. This is just like it would be without the bankruptcy filing. As long as you are current with the mortgage payments the bank will not foreclose.
If you are behind on your mortgage, or have a second mortgage, worry not, you will still be able to keep your home. In chapter 13 you are given up to 5 years to catch-up the missed mortgage payments under a court approved plan. Your bank will legally be barred from foreclosing during your bankrutpcy.
Additionally, in chapter 13 you may be able to eliminate your second mortgage and keep your home. In order to eliminate the second mortgage you will have to prove to the Court that the value of your home is less than the value of your first mortgage.