I have an 02 5-spd BMW 525i. Why does the engine knock and sometimes shut off ? on 2002 BMW 525i

The car knocks most when it's been sitting for a long time turned off. This is usually when it is most likely to shut off when I come to a stop and am not in gear.

The car also does not seem to accelarate as much in the lower gears (1-3) as it did prior to this problem.

The check engine light also recently came on.

I recently had the car serviced to repair a leaking oil pan, so I'm not sure if the two problems are related.

Asked by for the 2002 BMW 525i