          return open(nbuf, flags);
        }
        cnt_index--;
      }
      v4l_index++;
    }
  }
  
  static void camera_open(CameraState *s) {
    int ret;
 
</s> remove   s->sensor_fd = open_v4l_by_name_and_index("cam-sensor-driver", s->camera_num, O_RDWR | O_NONBLOCK);
 </s> add   s->sensor_fd = open_v4l_by_name_and_index("cam-sensor-driver", s->camera_num); </s> remove       cnt_index--;
 </s> add       index--; </s> remove // TODO: refactor this to somewhere nicer, perhaps use in camera_qcom as well
static int open_v4l_by_name_and_index(const char name[], int index, int flags) {
  char nbuf[0x100];
  int v4l_index = 0;
  int cnt_index = index;
  while (true) {
    snprintf(nbuf, sizeof(nbuf), "/sys/class/video4linux/v4l-subdev%d/name", v4l_index);
    FILE *f = fopen(nbuf, "rb");
    if (f == NULL) return -1;
    int len = fread(nbuf, 1, sizeof(nbuf), f);
    fclose(f);

    // name ends with '\n', remove it
    if (len < 1) return -1;
    nbuf[len-1] = '\0';

    if (strcmp(nbuf, name) == 0) {
      if (cnt_index == 0) {
        snprintf(nbuf, sizeof(nbuf), "/dev/v4l-subdev%d", v4l_index);
        LOGD("open %s for %s index %d", nbuf, name, index);
        return open(nbuf, flags);
 </s> add int open_v4l_by_name_and_index(const char name[], int index, int flags = O_RDWR | O_NONBLOCK) {
  for (int v4l_index = 0; /**/; ++v4l_index) {
    std::string v4l_name = util::read_file(util::string_format("/sys/class/video4linux/v4l-subdev%d/name", v4l_index));
    if (v4l_name.empty()) return -1;
    if (v4l_name.find(name) == 0) {
      if (index == 0) {
        return open(util::string_format("/dev/v4l-subdev%d", v4l_index).c_str(), flags); </s> remove   s->csiphy_fd = open_v4l_by_name_and_index("cam-csiphy-driver", s->camera_num, O_RDWR | O_NONBLOCK);
 </s> add   s->csiphy_fd = open_v4l_by_name_and_index("cam-csiphy-driver", s->camera_num);
          return open(nbuf, flags);
        }
        cnt_index--;
      }

    }
  }
  
  static void camera_open(CameraState *s) {
    int ret;
keep keep keep keep replace keep keep keep keep keep
 camera_qcom2: refactor open_v4l_by_name_and_index (#22067)

* refactor

* small cleanup

Co-authored-by: Willem Melching <willem.melching@gmail.com> 
selfdrive/camerad/cameras/camera_qcom2.cc