afu = cxl_pci_to_afu(dev);
 
-       get_device(&afu->dev);
        ctx = cxl_context_alloc();
        if (IS_ERR(ctx)) {
                rc = PTR_ERR(ctx);
 err_ctx:
        kfree(ctx);
 err_dev:
-       put_device(&afu->dev);
        return ERR_PTR(rc);
 }
 EXPORT_SYMBOL_GPL(cxl_dev_context_init);
        if (ctx->status >= STARTED)
                return -EBUSY;
 
-       put_device(&ctx->afu->dev);
-
        cxl_context_free(ctx);
 
        return 0;
 
        ctx->pe = i;
        ctx->elem = &ctx->afu->spa[i];
        ctx->pe_inserted = false;
+
+       /*
+        * take a ref on the afu so that it stays alive at-least till
+        * this context is reclaimed inside reclaim_ctx.
+        */
+       cxl_afu_get(afu);
        return 0;
 }
 
        if (ctx->irq_bitmap)
                kfree(ctx->irq_bitmap);
 
+       /* Drop ref to the afu device taken during cxl_context_init */
+       cxl_afu_put(ctx->afu);
+
        kfree(ctx);
 }
 
 
        bool enabled;
 };
 
+/* AFU refcount management */
+static inline struct cxl_afu *cxl_afu_get(struct cxl_afu *afu)
+{
+
+       return (get_device(&afu->dev) == NULL) ? NULL : afu;
+}
+
+static inline void  cxl_afu_put(struct cxl_afu *afu)
+{
+       put_device(&afu->dev);
+}
+
 
 struct cxl_irq_name {
        struct list_head list;
 
                spin_unlock(&adapter->afu_list_lock);
                goto err_put_adapter;
        }
-       get_device(&afu->dev);
+
+       /*
+        * taking a ref to the afu so that it doesn't go away
+        * for rest of the function. This ref is released before
+        * we return.
+        */
+       cxl_afu_get(afu);
        spin_unlock(&adapter->afu_list_lock);
 
        if (!afu->current_mode)
        file->private_data = ctx;
        cxl_ctx_get();
 
-       /* Our ref on the AFU will now hold the adapter */
-       put_device(&adapter->dev);
-
-       return 0;
+       /* indicate success */
+       rc = 0;
 
 err_put_afu:
-       put_device(&afu->dev);
+       /* release the ref taken earlier */
+       cxl_afu_put(afu);
 err_put_adapter:
        put_device(&adapter->dev);
        return rc;
                mutex_unlock(&ctx->mapping_lock);
        }
 
-       put_device(&ctx->afu->dev);
-
        /*
         * At this this point all bottom halfs have finished and we should be
         * getting no more IRQs from the hardware for this context.  Once it's