static int csi_get_upstream_endpoint(struct csi_priv *priv,
                                     struct v4l2_fwnode_endpoint *ep)
 {
-       struct device_node *endpoint, *port;
+       struct fwnode_handle *endpoint;
        struct v4l2_subdev *sd;
        struct media_pad *pad;
 
        if (!pad)
                return -ENODEV;
 
-       sd = media_entity_to_v4l2_subdev(pad->entity);
+       endpoint = imx_media_get_pad_fwnode(pad);
+       if (IS_ERR(endpoint))
+               return PTR_ERR(endpoint);
 
-       /*
-        * NOTE: this assumes an OF-graph port id is the same as a
-        * media pad index.
-        */
-       port = of_graph_get_port_by_id(sd->dev->of_node, pad->index);
-       if (!port)
-               return -ENODEV;
-
-       endpoint = of_get_next_child(port, NULL);
-       of_node_put(port);
-       if (!endpoint)
-               return -ENODEV;
+       v4l2_fwnode_endpoint_parse(endpoint, ep);
 
-       v4l2_fwnode_endpoint_parse(of_fwnode_handle(endpoint), ep);
-       of_node_put(endpoint);
+       fwnode_handle_put(endpoint);
 
        return 0;
 }
 
 }
 EXPORT_SYMBOL_GPL(imx_media_pipeline_video_device);
 
+/*
+ * Find a fwnode endpoint that maps to the given subdevice's pad.
+ * If there are multiple endpoints that map to the pad, only the
+ * first endpoint encountered is returned.
+ *
+ * On success the refcount of the returned fwnode endpoint is
+ * incremented.
+ */
+struct fwnode_handle *imx_media_get_pad_fwnode(struct media_pad *pad)
+{
+       struct fwnode_handle *endpoint;
+       struct v4l2_subdev *sd;
+
+       if (!is_media_entity_v4l2_subdev(pad->entity))
+               return ERR_PTR(-ENODEV);
+
+       sd = media_entity_to_v4l2_subdev(pad->entity);
+
+       fwnode_graph_for_each_endpoint(dev_fwnode(sd->dev), endpoint) {
+               int pad_idx = media_entity_get_fwnode_pad(&sd->entity,
+                                                         endpoint,
+                                                         pad->flags);
+               if (pad_idx < 0)
+                       continue;
+
+               if (pad_idx == pad->index)
+                       return endpoint;
+       }
+
+       return ERR_PTR(-ENODEV);
+}
+EXPORT_SYMBOL_GPL(imx_media_get_pad_fwnode);
+
 /*
  * Turn current pipeline streaming on/off starting from entity.
  */
 
 struct video_device *
 imx_media_pipeline_video_device(struct media_entity *start_entity,
                                enum v4l2_buf_type buftype, bool upstream);
+struct fwnode_handle *imx_media_get_pad_fwnode(struct media_pad *pad);
 
 struct imx_media_dma_buf {
        void          *virt;