refs: move for_each_*ref* functions into common code