struct ib_qp                 *qp;
        struct ib_uverbs_mcast_entry *mcast;
        int                           ret = -EINVAL;
+       bool                          found = false;
 
        if (copy_from_user(&cmd, buf, sizeof cmd))
                return -EFAULT;
        obj = container_of(qp->uobject, struct ib_uqp_object, uevent.uobject);
        mutex_lock(&obj->mcast_lock);
 
-       ret = ib_detach_mcast(qp, (union ib_gid *) cmd.gid, cmd.mlid);
-       if (ret)
-               goto out_put;
-
        list_for_each_entry(mcast, &obj->mcast_list, list)
                if (cmd.mlid == mcast->lid &&
                    !memcmp(cmd.gid, mcast->gid.raw, sizeof mcast->gid.raw)) {
                        list_del(&mcast->list);
                        kfree(mcast);
+                       found = true;
                        break;
                }
 
+       if (!found) {
+               ret = -EINVAL;
+               goto out_put;
+       }
+
+       ret = ib_detach_mcast(qp, (union ib_gid *)cmd.gid, cmd.mlid);
+
 out_put:
        mutex_unlock(&obj->mcast_lock);
        uobj_put_obj_read(qp);