- struct thandle *th = NULL;
- struct mdd_device *mdd = mdo2mdd(&obj->mod_obj);
- int rc = 0;
- ENTRY;
-
- th = mdd_trans_create(env, mdd);
- if (IS_ERR(th)) {
- CERROR("Cannot get thandle\n");
- RETURN(-ENOMEM);
- }
- rc = orph_declare_index_delete(env, obj, th);
- if (rc)
- GOTO(stop, rc);
-
- rc = mdo_declare_destroy(env, obj, th);
- if (rc)
- GOTO(stop, rc);
-
- rc = mdd_trans_start(env, mdd, th);
- if (rc)
- GOTO(stop, rc);
+ struct thandle *th = NULL;
+ struct mdd_device *mdd = mdo2mdd(&obj->mod_obj);
+ bool orphan_exists = true;
+ int rc = 0, rc1 = 0;
+ ENTRY;
+
+ th = mdd_trans_create(env, mdd);
+ if (IS_ERR(th)) {
+ rc = PTR_ERR(th);
+ if (rc != -EINPROGRESS)
+ CERROR("%s: cannot get orphan thandle: rc = %d\n",
+ mdd2obd_dev(mdd)->obd_name, rc);
+ RETURN(rc);
+ }
+
+ mdd_write_lock(env, obj, DT_TGT_CHILD);
+ rc = mdd_orphan_declare_delete(env, obj, th);
+ if (rc == -ENOENT || lu_object_is_dying(obj->mod_obj.mo_lu.lo_header))
+ orphan_exists = false;
+ else if (rc)
+ GOTO(unlock, rc);
+
+ if (orphan_exists) {
+ rc = mdo_declare_destroy(env, obj, th);
+ if (rc)
+ GOTO(unlock, rc);
+ }
+
+ rc = mdd_trans_start(env, mdd, th);
+ if (rc)
+ GOTO(unlock, rc);