Most common cause of a surge is an air leak. The computer is getting signals from the mass airflow sensor, oxygen sensors, and other sensors that don't make sense, and it tries to compensate using the idle air control valve, timing, and injector duration, but the way the engine responds to adjustment does not make sense to its program because the program does not anticipate an air leak. The computer tries to correct the mixture by adding fuel, so now it has too much air and too much fuel, so the engine speeds up. That reduces intake manifold vacuum, so the leak tends to flow less unwanted air, so the problem is reduced, the engine slows down, and the cycle repeats.

First thing to check is leaks in the air inlet ductwork. I have replaced the rubber throttle body hood on both of my '04s already.

Next thing to check is vacuum leak. Look at vacuum hoses and spray diesel starting fluid around intake manifold and see if you get a reaction. The Volvo my older daughter drove to college once had a crazy surging idle that turned out to be an intake manifold gasket that was leaking all the way across. I had done the head gasket on that car a couple of years earlier, so the intake manifold gasket was not very old. It was just a crappy gasket.

You can also have problems with an exhaust manifold leak that sucks air under certain conditions, confusing the oxygen sensors. If the computer code is for oxygen sensor or catalytic converter, and the car is surging, look for an exhaust leak. If the code is for the mass airflow sensor, look for an intake ductwork leak. I have read that the older BMWs have problems with leaks around injectors and the throttle body and shaft, but I have not seen those on my e36s or e46s.

Hope it is not the PCV because working on the PCV on these cars is a huge PITA. I took the PCV off my 325 to check and clean it, and though it seemed fine, it was so much work that I bought a new one to put back on because I do NOT want to fool with that thing again for a very long time. If you have to replace the intake manifold gasket to cure a vacuum leak, be sure and use that opportunity to clean or replace the PCV. It has to be much easier with the manifold off.