Whamcloud - gitweb
LU-4525 lfsck: distinguish objects visibility by LFSCK
[fs/lustre-release.git] / lustre / osd-ldiskfs / osd_handler.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2013, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/osd/osd_handler.c
37  *
38  * Top-level entry points into osd module
39  *
40  * Author: Nikita Danilov <nikita@clusterfs.com>
41  *         Pravin Shelar <pravin.shelar@sun.com> : Added fid in dirent
42  */
43
44 #define DEBUG_SUBSYSTEM S_MDS
45
46 #include <linux/module.h>
47
48 /* LUSTRE_VERSION_CODE */
49 #include <lustre_ver.h>
50 /* prerequisite for linux/xattr.h */
51 #include <linux/types.h>
52 /* prerequisite for linux/xattr.h */
53 #include <linux/fs.h>
54 /* XATTR_{REPLACE,CREATE} */
55 #include <linux/xattr.h>
56
57 /*
58  * struct OBD_{ALLOC,FREE}*()
59  * OBD_FAIL_CHECK
60  */
61 #include <obd_support.h>
62 /* struct ptlrpc_thread */
63 #include <lustre_net.h>
64 #include <lustre_fid.h>
65 /* process_config */
66 #include <lustre_param.h>
67
68 #include "osd_internal.h"
69 #include "osd_dynlocks.h"
70
71 /* llo_* api support */
72 #include <md_object.h>
73 #include <lustre_quota.h>
74
75 int ldiskfs_pdo = 1;
76 CFS_MODULE_PARM(ldiskfs_pdo, "i", int, 0644,
77                 "ldiskfs with parallel directory operations");
78
79 int ldiskfs_track_declares_assert;
80 CFS_MODULE_PARM(ldiskfs_track_declares_assert, "i", int, 0644,
81                 "LBUG during tracking of declares");
82
83 /* Slab to allocate dynlocks */
84 struct kmem_cache *dynlock_cachep;
85
86 static struct lu_kmem_descr ldiskfs_caches[] = {
87         {
88                 .ckd_cache = &dynlock_cachep,
89                 .ckd_name  = "dynlock_cache",
90                 .ckd_size  = sizeof(struct dynlock_handle)
91         },
92         {
93                 .ckd_cache = NULL
94         }
95 };
96
97 static const char dot[] = ".";
98 static const char dotdot[] = "..";
99 static const char remote_obj_dir[] = "REM_OBJ_DIR";
100
101 static const struct lu_object_operations      osd_lu_obj_ops;
102 static const struct dt_object_operations      osd_obj_ops;
103 static const struct dt_object_operations      osd_obj_ea_ops;
104 static const struct dt_object_operations      osd_obj_otable_it_ops;
105 static const struct dt_index_operations       osd_index_iam_ops;
106 static const struct dt_index_operations       osd_index_ea_ops;
107
108 int osd_trans_declare_op2rb[] = {
109         [OSD_OT_ATTR_SET]       = OSD_OT_ATTR_SET,
110         [OSD_OT_PUNCH]          = OSD_OT_MAX,
111         [OSD_OT_XATTR_SET]      = OSD_OT_XATTR_SET,
112         [OSD_OT_CREATE]         = OSD_OT_DESTROY,
113         [OSD_OT_DESTROY]        = OSD_OT_CREATE,
114         [OSD_OT_REF_ADD]        = OSD_OT_REF_DEL,
115         [OSD_OT_REF_DEL]        = OSD_OT_REF_ADD,
116         [OSD_OT_WRITE]          = OSD_OT_WRITE,
117         [OSD_OT_INSERT]         = OSD_OT_DELETE,
118         [OSD_OT_DELETE]         = OSD_OT_INSERT,
119         [OSD_OT_UPDATE]         = OSD_OT_MAX,
120         [OSD_OT_QUOTA]          = OSD_OT_MAX,
121 };
122
123 static int osd_has_index(const struct osd_object *obj)
124 {
125         return obj->oo_dt.do_index_ops != NULL;
126 }
127
128 static int osd_object_invariant(const struct lu_object *l)
129 {
130         return osd_invariant(osd_obj(l));
131 }
132
133 /*
134  * Concurrency: doesn't matter
135  */
136 static int osd_read_locked(const struct lu_env *env, struct osd_object *o)
137 {
138         return osd_oti_get(env)->oti_r_locks > 0;
139 }
140
141 /*
142  * Concurrency: doesn't matter
143  */
144 static int osd_write_locked(const struct lu_env *env, struct osd_object *o)
145 {
146         struct osd_thread_info *oti = osd_oti_get(env);
147         return oti->oti_w_locks > 0 && o->oo_owner == env;
148 }
149
150 /*
151  * Concurrency: doesn't access mutable data
152  */
153 static int osd_root_get(const struct lu_env *env,
154                         struct dt_device *dev, struct lu_fid *f)
155 {
156         lu_local_obj_fid(f, OSD_FS_ROOT_OID);
157         return 0;
158 }
159
160 /*
161  * OSD object methods.
162  */
163
164 /*
165  * Concurrency: no concurrent access is possible that early in object
166  * life-cycle.
167  */
168 static struct lu_object *osd_object_alloc(const struct lu_env *env,
169                                           const struct lu_object_header *hdr,
170                                           struct lu_device *d)
171 {
172         struct osd_object *mo;
173
174         OBD_ALLOC_PTR(mo);
175         if (mo != NULL) {
176                 struct lu_object *l;
177
178                 l = &mo->oo_dt.do_lu;
179                 dt_object_init(&mo->oo_dt, NULL, d);
180                 mo->oo_dt.do_ops = &osd_obj_ea_ops;
181                 l->lo_ops = &osd_lu_obj_ops;
182                 init_rwsem(&mo->oo_sem);
183                 init_rwsem(&mo->oo_ext_idx_sem);
184                 spin_lock_init(&mo->oo_guard);
185                 return l;
186         } else {
187                 return NULL;
188         }
189 }
190
191 int osd_get_lma(struct osd_thread_info *info, struct inode *inode,
192                 struct dentry *dentry, struct lustre_mdt_attrs *lma)
193 {
194         int rc;
195
196         CLASSERT(LMA_OLD_SIZE >= sizeof(*lma));
197         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
198                              info->oti_mdt_attrs_old, LMA_OLD_SIZE);
199         if (rc > 0) {
200                 if ((void *)lma != (void *)info->oti_mdt_attrs_old)
201                         memcpy(lma, info->oti_mdt_attrs_old, sizeof(*lma));
202                 rc = 0;
203                 lustre_lma_swab(lma);
204                 /* Check LMA compatibility */
205                 if (lma->lma_incompat & ~LMA_INCOMPAT_SUPP) {
206                         CWARN("%.16s: unsupported incompat LMA feature(s) %#x "
207                               "for fid = "DFID", ino = %lu\n",
208                               LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
209                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
210                               PFID(&lma->lma_self_fid), inode->i_ino);
211                         rc = -EOPNOTSUPP;
212                 }
213         } else if (rc == 0) {
214                 rc = -ENODATA;
215         }
216
217         return rc;
218 }
219
220 /*
221  * retrieve object from backend ext fs.
222  **/
223 struct inode *osd_iget(struct osd_thread_info *info, struct osd_device *dev,
224                        struct osd_inode_id *id)
225 {
226         struct inode *inode = NULL;
227
228         inode = ldiskfs_iget(osd_sb(dev), id->oii_ino);
229         if (IS_ERR(inode)) {
230                 CDEBUG(D_INODE, "no inode: ino = %u, rc = %ld\n",
231                        id->oii_ino, PTR_ERR(inode));
232         } else if (id->oii_gen != OSD_OII_NOGEN &&
233                    inode->i_generation != id->oii_gen) {
234                 CDEBUG(D_INODE, "unmatched inode: ino = %u, oii_gen = %u, "
235                        "i_generation = %u\n",
236                        id->oii_ino, id->oii_gen, inode->i_generation);
237                 iput(inode);
238                 inode = ERR_PTR(-ESTALE);
239         } else if (inode->i_nlink == 0) {
240                 /* due to parallel readdir and unlink,
241                 * we can have dead inode here. */
242                 CDEBUG(D_INODE, "stale inode: ino = %u\n", id->oii_ino);
243                 iput(inode);
244                 inode = ERR_PTR(-ESTALE);
245         } else if (is_bad_inode(inode)) {
246                 CWARN("%.16s: bad inode: ino = %u\n",
247                 LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name, id->oii_ino);
248                 iput(inode);
249                 inode = ERR_PTR(-ENOENT);
250         } else {
251                 if (id->oii_gen == OSD_OII_NOGEN)
252                         osd_id_gen(id, inode->i_ino, inode->i_generation);
253
254                 /* Do not update file c/mtime in ldiskfs.
255                  * NB: we don't have any lock to protect this because we don't
256                  * have reference on osd_object now, but contention with
257                  * another lookup + attr_set can't happen in the tiny window
258                  * between if (...) and set S_NOCMTIME. */
259                 if (!(inode->i_flags & S_NOCMTIME))
260                         inode->i_flags |= S_NOCMTIME;
261         }
262         return inode;
263 }
264
265 static struct inode *
266 osd_iget_fid(struct osd_thread_info *info, struct osd_device *dev,
267              struct osd_inode_id *id, struct lu_fid *fid)
268 {
269         struct lustre_mdt_attrs *lma   = &info->oti_mdt_attrs;
270         struct inode            *inode;
271         int                      rc;
272
273         inode = osd_iget(info, dev, id);
274         if (IS_ERR(inode))
275                 return inode;
276
277         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
278         if (rc == 0) {
279                 *fid = lma->lma_self_fid;
280         } else if (rc == -ENODATA) {
281                 if (unlikely(inode == osd_sb(dev)->s_root->d_inode))
282                         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
283                 else
284                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
285         } else {
286                 iput(inode);
287                 inode = ERR_PTR(rc);
288         }
289         return inode;
290 }
291
292 static struct inode *osd_iget_check(struct osd_thread_info *info,
293                                     struct osd_device *dev,
294                                     const struct lu_fid *fid,
295                                     struct osd_inode_id *id,
296                                     bool in_oi)
297 {
298         struct inode    *inode;
299         int              rc     = 0;
300         ENTRY;
301
302         inode = ldiskfs_iget(osd_sb(dev), id->oii_ino);
303         if (IS_ERR(inode)) {
304                 rc = PTR_ERR(inode);
305                 if (!in_oi || (rc != -ENOENT && rc != -ESTALE)) {
306                         CDEBUG(D_INODE, "no inode: ino = %u, rc = %d\n",
307                                id->oii_ino, rc);
308
309                         GOTO(put, rc);
310                 }
311
312                 goto check_oi;
313         }
314
315         if (is_bad_inode(inode)) {
316                 rc = -ENOENT;
317                 if (!in_oi) {
318                         CDEBUG(D_INODE, "bad inode: ino = %u\n", id->oii_ino);
319
320                         GOTO(put, rc);
321                 }
322
323                 goto check_oi;
324         }
325
326         if (id->oii_gen != OSD_OII_NOGEN &&
327             inode->i_generation != id->oii_gen) {
328                 rc = -ESTALE;
329                 if (!in_oi) {
330                         CDEBUG(D_INODE, "unmatched inode: ino = %u, "
331                                "oii_gen = %u, i_generation = %u\n",
332                                id->oii_ino, id->oii_gen, inode->i_generation);
333
334                         GOTO(put, rc);
335                 }
336
337                 goto check_oi;
338         }
339
340         if (inode->i_nlink == 0) {
341                 rc = -ENOENT;
342                 if (!in_oi) {
343                         CDEBUG(D_INODE, "stale inode: ino = %u\n", id->oii_ino);
344
345                         GOTO(put, rc);
346                 }
347
348                 goto check_oi;
349         }
350
351 check_oi:
352         if (rc != 0) {
353                 LASSERTF(rc == -ESTALE || rc == -ENOENT, "rc = %d\n", rc);
354
355                 rc = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
356                 /* XXX: There are some possible cases:
357                  *      1. rc = 0.
358                  *         Backup/restore caused the OI invalid.
359                  *      2. rc = 0.
360                  *         Someone unlinked the object but NOT removed
361                  *         the OI mapping, such as mount target device
362                  *         as ldiskfs, and modify something directly.
363                  *      3. rc = -ENOENT.
364                  *         Someone just removed the object between the
365                  *         former oi_lookup and the iget. It is normal.
366                  *      4. Other failure cases.
367                  *
368                  *      Generally, when the device is mounted, it will
369                  *      auto check whether the system is restored from
370                  *      file-level backup or not. We trust such detect
371                  *      to distinguish the 1st case from the 2nd case. */
372                 if (rc == 0) {
373                         if (!IS_ERR(inode) && inode->i_generation != 0 &&
374                             inode->i_generation == id->oii_gen)
375                                 rc = -ENOENT;
376                         else
377                                 rc = -EREMCHG;
378                 }
379         } else {
380                 if (id->oii_gen == OSD_OII_NOGEN)
381                         osd_id_gen(id, inode->i_ino, inode->i_generation);
382
383                 /* Do not update file c/mtime in ldiskfs.
384                  * NB: we don't have any lock to protect this because we don't
385                  * have reference on osd_object now, but contention with
386                  * another lookup + attr_set can't happen in the tiny window
387                  * between if (...) and set S_NOCMTIME. */
388                 if (!(inode->i_flags & S_NOCMTIME))
389                         inode->i_flags |= S_NOCMTIME;
390         }
391
392         GOTO(put, rc);
393
394 put:
395         if (rc != 0) {
396                 if (!IS_ERR(inode))
397                         iput(inode);
398
399                 inode = ERR_PTR(rc);
400         }
401
402         return inode;
403 }
404
405 /**
406  * \retval +v: new filter_fid, does not contain self-fid
407  * \retval 0:  filter_fid_old, contains self-fid
408  * \retval -v: other failure cases
409  */
410 int osd_get_idif(struct osd_thread_info *info, struct inode *inode,
411                  struct dentry *dentry, struct lu_fid *fid)
412 {
413         struct filter_fid_old   *ff     = &info->oti_ff;
414         struct ost_id           *ostid  = &info->oti_ostid;
415         int                      rc;
416
417         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_FID, ff, sizeof(*ff));
418         if (rc == sizeof(*ff)) {
419                 rc = 0;
420                 ostid_set_seq(ostid, le64_to_cpu(ff->ff_seq));
421                 ostid_set_id(ostid, le64_to_cpu(ff->ff_objid));
422                 /* XXX: should use real OST index in the future. LU-3569 */
423                 ostid_to_fid(fid, ostid, 0);
424         } else if (rc == sizeof(struct filter_fid)) {
425                 rc = 1;
426         } else if (rc >= 0) {
427                 rc = -EINVAL;
428         }
429
430         return rc;
431 }
432
433 static int osd_lma_self_repair(struct osd_thread_info *info,
434                                struct osd_device *osd, struct inode *inode,
435                                const struct lu_fid *fid, __u32 compat)
436 {
437         handle_t *jh;
438         int       rc;
439
440         LASSERT(current->journal_info == NULL);
441
442         jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC,
443                                   osd_dto_credits_noquota[DTO_XATTR_SET]);
444         if (IS_ERR(jh)) {
445                 rc = PTR_ERR(jh);
446                 CWARN("%s: cannot start journal for lma_self_repair: rc = %d\n",
447                       osd_name(osd), rc);
448                 return rc;
449         }
450
451         rc = osd_ea_fid_set(info, inode, fid, compat, 0);
452         if (rc != 0)
453                 CWARN("%s: cannot self repair the LMA: rc = %d\n",
454                       osd_name(osd), rc);
455         ldiskfs_journal_stop(jh);
456         return rc;
457 }
458
459 static int osd_check_lma(const struct lu_env *env, struct osd_object *obj)
460 {
461         struct osd_thread_info  *info   = osd_oti_get(env);
462         struct osd_device       *osd    = osd_obj2dev(obj);
463         struct lustre_mdt_attrs *lma    = &info->oti_mdt_attrs;
464         struct inode            *inode  = obj->oo_inode;
465         struct dentry           *dentry = &info->oti_obj_dentry;
466         struct lu_fid           *fid    = NULL;
467         const struct lu_fid     *rfid   = lu_object_fid(&obj->oo_dt.do_lu);
468         int                      rc;
469         ENTRY;
470
471         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_COMPAT_INVALID_ENTRY))
472                 RETURN(0);
473
474         CLASSERT(LMA_OLD_SIZE >= sizeof(*lma));
475         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
476                              info->oti_mdt_attrs_old, LMA_OLD_SIZE);
477         if (rc == -ENODATA && !fid_is_igif(rfid) && osd->od_check_ff) {
478                 fid = &lma->lma_self_fid;
479                 rc = osd_get_idif(info, inode, dentry, fid);
480                 if ((rc > 0) || (rc == -ENODATA && osd->od_lma_self_repair)) {
481                         /* For the given OST-object, if it has neither LMA nor
482                          * FID in XATTR_NAME_FID, then the given FID (which is
483                          * contained in the @obj, from client RPC for locating
484                          * the OST-object) is trusted. We use it to generate
485                          * the LMA. */
486                         osd_lma_self_repair(info, osd, inode, rfid,
487                                 fid_is_on_ost(info, osd, fid, OI_CHECK_FLD) ?
488                                 LMAC_FID_ON_OST : 0);
489                         RETURN(0);
490                 }
491         }
492
493         if (unlikely(rc == -ENODATA))
494                 RETURN(0);
495
496         if (rc < 0)
497                 RETURN(rc);
498
499         if (rc > 0) {
500                 rc = 0;
501                 lustre_lma_swab(lma);
502                 if (unlikely((lma->lma_incompat & ~LMA_INCOMPAT_SUPP) ||
503                              CFS_FAIL_CHECK(OBD_FAIL_OSD_LMA_INCOMPAT))) {
504                         CWARN("%s: unsupported incompat LMA feature(s) %#x for "
505                               "fid = "DFID", ino = %lu\n", osd_name(osd),
506                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
507                               PFID(rfid), inode->i_ino);
508                         rc = -EOPNOTSUPP;
509                 } else if (!(lma->lma_compat & LMAC_NOT_IN_OI)) {
510                         fid = &lma->lma_self_fid;
511                 }
512         }
513
514         if (fid != NULL && unlikely(!lu_fid_eq(rfid, fid))) {
515                 if (fid_is_idif(rfid) && fid_is_idif(fid)) {
516                         struct ost_id   *oi   = &info->oti_ostid;
517                         struct lu_fid   *fid1 = &info->oti_fid3;
518                         __u32            idx  = fid_idif_ost_idx(rfid);
519
520                         /* For old IDIF, the OST index is not part of the IDIF,
521                          * Means that different OSTs may have the same IDIFs.
522                          * Under such case, we need to make some compatible
523                          * check to make sure to trigger OI scrub properly. */
524                         if (idx != 0 && fid_idif_ost_idx(fid) == 0) {
525                                 /* Given @rfid is new, LMA is old. */
526                                 fid_to_ostid(fid, oi);
527                                 ostid_to_fid(fid1, oi, idx);
528                                 if (lu_fid_eq(fid1, rfid)) {
529                                         if (osd->od_lma_self_repair)
530                                                 osd_lma_self_repair(info, osd,
531                                                         inode, rfid,
532                                                         LMAC_FID_ON_OST);
533                                         RETURN(0);
534                                 }
535                         }
536                 }
537
538                 CDEBUG(D_INODE, "%s: FID "DFID" != self_fid "DFID"\n",
539                        osd_name(osd), PFID(rfid), PFID(fid));
540                 rc = -EREMCHG;
541         }
542
543         RETURN(rc);
544 }
545
546 static int osd_fid_lookup(const struct lu_env *env, struct osd_object *obj,
547                           const struct lu_fid *fid,
548                           const struct lu_object_conf *conf)
549 {
550         struct osd_thread_info *info;
551         struct lu_device       *ldev   = obj->oo_dt.do_lu.lo_dev;
552         struct osd_device      *dev;
553         struct osd_idmap_cache *oic;
554         struct osd_inode_id    *id;
555         struct inode           *inode;
556         struct osd_scrub       *scrub;
557         struct scrub_file      *sf;
558         int                     result;
559         int                     saved  = 0;
560         bool                    in_oi  = false;
561         bool                    triggered = false;
562         ENTRY;
563
564         LINVRNT(osd_invariant(obj));
565         LASSERT(obj->oo_inode == NULL);
566         LASSERTF(fid_is_sane(fid) || fid_is_idif(fid), DFID, PFID(fid));
567
568         dev = osd_dev(ldev);
569         scrub = &dev->od_scrub;
570         sf = &scrub->os_file;
571         info = osd_oti_get(env);
572         LASSERT(info);
573         oic = &info->oti_cache;
574
575         if (OBD_FAIL_CHECK(OBD_FAIL_OST_ENOENT))
576                 RETURN(-ENOENT);
577
578         /* For the object is created as locking anchor, or for the object to
579          * be created on disk. No need to osd_oi_lookup() at here because FID
580          * shouldn't never be re-used, if it's really a duplicate FID from
581          * unexpected reason, we should be able to detect it later by calling
582          * do_create->osd_oi_insert(). */
583         if (conf != NULL && conf->loc_flags & LOC_F_NEW)
584                 GOTO(out, result = 0);
585
586         /* Search order: 1. per-thread cache. */
587         if (lu_fid_eq(fid, &oic->oic_fid) &&
588             likely(oic->oic_dev == dev)) {
589                 id = &oic->oic_lid;
590                 goto iget;
591         }
592
593         id = &info->oti_id;
594         if (!cfs_list_empty(&scrub->os_inconsistent_items)) {
595                 /* Search order: 2. OI scrub pending list. */
596                 result = osd_oii_lookup(dev, fid, id);
597                 if (result == 0)
598                         goto iget;
599         }
600
601         /* Search order: 3. OI files. */
602         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
603         if (result == -ENOENT) {
604                 if (!fid_is_norm(fid) ||
605                     fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) ||
606                     !ldiskfs_test_bit(osd_oi_fid2idx(dev,fid),
607                                       sf->sf_oi_bitmap))
608                         GOTO(out, result = 0);
609
610                 goto trigger;
611         }
612
613         if (result != 0)
614                 GOTO(out, result);
615
616         in_oi = true;
617
618 iget:
619         inode = osd_iget_check(info, dev, fid, id, in_oi);
620         if (IS_ERR(inode)) {
621                 result = PTR_ERR(inode);
622                 if (result == -ENOENT || result == -ESTALE) {
623                         if (!in_oi)
624                                 fid_zero(&oic->oic_fid);
625
626                         GOTO(out, result = -ENOENT);
627                 } else if (result == -EREMCHG) {
628
629 trigger:
630                         if (!in_oi)
631                                 fid_zero(&oic->oic_fid);
632
633                         if (unlikely(triggered))
634                                 GOTO(out, result = saved);
635
636                         triggered = true;
637                         if (thread_is_running(&scrub->os_thread)) {
638                                 result = -EINPROGRESS;
639                         } else if (!dev->od_noscrub) {
640                                 result = osd_scrub_start(dev);
641                                 LCONSOLE_WARN("%.16s: trigger OI scrub by RPC "
642                                               "for "DFID", rc = %d [1]\n",
643                                               osd_name(dev), PFID(fid),result);
644                                 if (result == 0 || result == -EALREADY)
645                                         result = -EINPROGRESS;
646                                 else
647                                         result = -EREMCHG;
648                         }
649
650                         /* We still have chance to get the valid inode: for the
651                          * object which is referenced by remote name entry, the
652                          * object on the local MDT will be linked under the dir
653                          * of "/REMOTE_PARENT_DIR" with its FID string as name.
654                          *
655                          * We do not know whether the object for the given FID
656                          * is referenced by some remote name entry or not, and
657                          * especially for DNE II, a multiple-linked object may
658                          * have many name entries reside on many MDTs.
659                          *
660                          * To simplify the operation, OSD will not distinguish
661                          * more, just lookup "/REMOTE_PARENT_DIR". Usually, it
662                          * only happened for the RPC from other MDT during the
663                          * OI scrub, or for the client side RPC with FID only,
664                          * such as FID to path, or from old connected client. */
665                         saved = result;
666                         result = osd_lookup_in_remote_parent(info, dev,
667                                                              fid, id);
668                         if (result == 0) {
669                                 in_oi = false;
670                                 goto iget;
671                         }
672
673                         result = saved;
674                 }
675
676                 GOTO(out, result);
677         }
678
679         obj->oo_inode = inode;
680         LASSERT(obj->oo_inode->i_sb == osd_sb(dev));
681
682         result = osd_check_lma(env, obj);
683         if (result != 0) {
684                 iput(inode);
685                 obj->oo_inode = NULL;
686                 if (result == -EREMCHG) {
687                         if (!in_oi) {
688                                 result = osd_oi_lookup(info, dev, fid, id,
689                                                        OI_CHECK_FLD);
690                                 if (result != 0) {
691                                         fid_zero(&oic->oic_fid);
692                                         GOTO(out, result);
693                                 }
694                         }
695
696                         goto trigger;
697                 }
698
699                 GOTO(out, result);
700         }
701
702         obj->oo_compat_dot_created = 1;
703         obj->oo_compat_dotdot_created = 1;
704
705         if (!S_ISDIR(inode->i_mode) || !ldiskfs_pdo) /* done */
706                 GOTO(out, result = 0);
707
708         LASSERT(obj->oo_hl_head == NULL);
709         obj->oo_hl_head = ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
710         if (obj->oo_hl_head == NULL) {
711                 obj->oo_inode = NULL;
712                 iput(inode);
713                 GOTO(out, result = -ENOMEM);
714         }
715         GOTO(out, result = 0);
716
717 out:
718         LINVRNT(osd_invariant(obj));
719         return result;
720 }
721
722 /*
723  * Concurrency: shouldn't matter.
724  */
725 static void osd_object_init0(struct osd_object *obj)
726 {
727         LASSERT(obj->oo_inode != NULL);
728         obj->oo_dt.do_body_ops = &osd_body_ops;
729         obj->oo_dt.do_lu.lo_header->loh_attr |=
730                 (LOHA_EXISTS | (obj->oo_inode->i_mode & S_IFMT));
731 }
732
733 /*
734  * Concurrency: no concurrent access is possible that early in object
735  * life-cycle.
736  */
737 static int osd_object_init(const struct lu_env *env, struct lu_object *l,
738                            const struct lu_object_conf *conf)
739 {
740         struct osd_object *obj = osd_obj(l);
741         int result;
742
743         LINVRNT(osd_invariant(obj));
744
745         if (fid_is_otable_it(&l->lo_header->loh_fid)) {
746                 obj->oo_dt.do_ops = &osd_obj_otable_it_ops;
747                 l->lo_header->loh_attr |= LOHA_EXISTS;
748                 return 0;
749         }
750
751         result = osd_fid_lookup(env, obj, lu_object_fid(l), conf);
752         obj->oo_dt.do_body_ops = &osd_body_ops_new;
753         if (result == 0 && obj->oo_inode != NULL)
754                 osd_object_init0(obj);
755
756         LINVRNT(osd_invariant(obj));
757         return result;
758 }
759
760 /*
761  * Concurrency: no concurrent access is possible that late in object
762  * life-cycle.
763  */
764 static void osd_object_free(const struct lu_env *env, struct lu_object *l)
765 {
766         struct osd_object *obj = osd_obj(l);
767
768         LINVRNT(osd_invariant(obj));
769
770         dt_object_fini(&obj->oo_dt);
771         if (obj->oo_hl_head != NULL)
772                 ldiskfs_htree_lock_head_free(obj->oo_hl_head);
773         OBD_FREE_PTR(obj);
774 }
775
776 /*
777  * Concurrency: no concurrent access is possible that late in object
778  * life-cycle.
779  */
780 static void osd_index_fini(struct osd_object *o)
781 {
782         struct iam_container *bag;
783
784         if (o->oo_dir != NULL) {
785                 bag = &o->oo_dir->od_container;
786                 if (o->oo_inode != NULL) {
787                         if (bag->ic_object == o->oo_inode)
788                                 iam_container_fini(bag);
789                 }
790                 OBD_FREE_PTR(o->oo_dir);
791                 o->oo_dir = NULL;
792         }
793 }
794
795 /*
796  * Concurrency: no concurrent access is possible that late in object
797  * life-cycle (for all existing callers, that is. New callers have to provide
798  * their own locking.)
799  */
800 static int osd_inode_unlinked(const struct inode *inode)
801 {
802         return inode->i_nlink == 0;
803 }
804
805 enum {
806         OSD_TXN_OI_DELETE_CREDITS    = 20,
807         OSD_TXN_INODE_DELETE_CREDITS = 20
808 };
809
810 /*
811  * Journal
812  */
813
814 #if OSD_THANDLE_STATS
815 /**
816  * Set time when the handle is allocated
817  */
818 static void osd_th_alloced(struct osd_thandle *oth)
819 {
820         oth->oth_alloced = cfs_time_current();
821 }
822
823 /**
824  * Set time when the handle started
825  */
826 static void osd_th_started(struct osd_thandle *oth)
827 {
828         oth->oth_started = cfs_time_current();
829 }
830
831 /**
832  * Helper function to convert time interval to microseconds packed in
833  * long int.
834  */
835 static long interval_to_usec(cfs_time_t start, cfs_time_t end)
836 {
837         struct timeval val;
838
839         cfs_duration_usec(cfs_time_sub(end, start), &val);
840         return val.tv_sec * 1000000 + val.tv_usec;
841 }
842
843 /**
844  * Check whether the we deal with this handle for too long.
845  */
846 static void __osd_th_check_slow(void *oth, struct osd_device *dev,
847                                 cfs_time_t alloced, cfs_time_t started,
848                                 cfs_time_t closed)
849 {
850         cfs_time_t now = cfs_time_current();
851
852         LASSERT(dev != NULL);
853
854         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_STARTING,
855                             interval_to_usec(alloced, started));
856         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_OPEN,
857                             interval_to_usec(started, closed));
858         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_CLOSING,
859                             interval_to_usec(closed, now));
860
861         if (cfs_time_before(cfs_time_add(alloced, cfs_time_seconds(30)), now)) {
862                 CWARN("transaction handle %p was open for too long: "
863                       "now "CFS_TIME_T" ,"
864                       "alloced "CFS_TIME_T" ,"
865                       "started "CFS_TIME_T" ,"
866                       "closed "CFS_TIME_T"\n",
867                       oth, now, alloced, started, closed);
868                 libcfs_debug_dumpstack(NULL);
869         }
870 }
871
872 #define OSD_CHECK_SLOW_TH(oth, dev, expr)                               \
873 {                                                                       \
874         cfs_time_t __closed = cfs_time_current();                       \
875         cfs_time_t __alloced = oth->oth_alloced;                        \
876         cfs_time_t __started = oth->oth_started;                        \
877                                                                         \
878         expr;                                                           \
879         __osd_th_check_slow(oth, dev, __alloced, __started, __closed);  \
880 }
881
882 #else /* OSD_THANDLE_STATS */
883
884 #define osd_th_alloced(h)                  do {} while(0)
885 #define osd_th_started(h)                  do {} while(0)
886 #define OSD_CHECK_SLOW_TH(oth, dev, expr)  expr
887
888 #endif /* OSD_THANDLE_STATS */
889
890 /*
891  * Concurrency: doesn't access mutable data.
892  */
893 static int osd_param_is_not_sane(const struct osd_device *dev,
894                                  const struct thandle *th)
895 {
896         struct osd_thandle *oh = container_of(th, typeof(*oh), ot_super);
897
898         return oh->ot_credits > osd_journal(dev)->j_max_transaction_buffers;
899 }
900
901 /*
902  * Concurrency: shouldn't matter.
903  */
904 static void osd_trans_commit_cb(struct super_block *sb,
905                                 struct ldiskfs_journal_cb_entry *jcb, int error)
906 {
907         struct osd_thandle *oh = container_of0(jcb, struct osd_thandle, ot_jcb);
908         struct thandle     *th  = &oh->ot_super;
909         struct lu_device   *lud = &th->th_dev->dd_lu_dev;
910         struct dt_txn_commit_cb *dcb, *tmp;
911
912         LASSERT(oh->ot_handle == NULL);
913
914         if (error)
915                 CERROR("transaction @0x%p commit error: %d\n", th, error);
916
917         dt_txn_hook_commit(th);
918
919         /* call per-transaction callbacks if any */
920         cfs_list_for_each_entry_safe(dcb, tmp, &oh->ot_dcb_list, dcb_linkage) {
921                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
922                          "commit callback entry: magic=%x name='%s'\n",
923                          dcb->dcb_magic, dcb->dcb_name);
924                 cfs_list_del_init(&dcb->dcb_linkage);
925                 dcb->dcb_func(NULL, th, dcb, error);
926         }
927
928         lu_ref_del_at(&lud->ld_reference, &oh->ot_dev_link, "osd-tx", th);
929         lu_device_put(lud);
930         th->th_dev = NULL;
931
932         lu_context_exit(&th->th_ctx);
933         lu_context_fini(&th->th_ctx);
934         OBD_FREE_PTR(oh);
935 }
936
937 static struct thandle *osd_trans_create(const struct lu_env *env,
938                                         struct dt_device *d)
939 {
940         struct osd_thread_info  *oti = osd_oti_get(env);
941         struct osd_iobuf        *iobuf = &oti->oti_iobuf;
942         struct osd_thandle      *oh;
943         struct thandle          *th;
944         ENTRY;
945
946         /* on pending IO in this thread should left from prev. request */
947         LASSERT(atomic_read(&iobuf->dr_numreqs) == 0);
948
949         th = ERR_PTR(-ENOMEM);
950         OBD_ALLOC_GFP(oh, sizeof *oh, __GFP_IO);
951         if (oh != NULL) {
952                 oh->ot_quota_trans = &oti->oti_quota_trans;
953                 memset(oh->ot_quota_trans, 0, sizeof(*oh->ot_quota_trans));
954                 th = &oh->ot_super;
955                 th->th_dev = d;
956                 th->th_result = 0;
957                 th->th_tags = LCT_TX_HANDLE;
958                 oh->ot_credits = 0;
959                 oti->oti_dev = osd_dt_dev(d);
960                 CFS_INIT_LIST_HEAD(&oh->ot_dcb_list);
961                 osd_th_alloced(oh);
962
963                 memset(oti->oti_declare_ops, 0,
964                                         sizeof(oti->oti_declare_ops));
965                 memset(oti->oti_declare_ops_rb, 0,
966                                         sizeof(oti->oti_declare_ops_rb));
967                 memset(oti->oti_declare_ops_cred, 0,
968                                         sizeof(oti->oti_declare_ops_cred));
969                 oti->oti_rollback = false;
970         }
971         RETURN(th);
972 }
973
974 /*
975  * Concurrency: shouldn't matter.
976  */
977 int osd_trans_start(const struct lu_env *env, struct dt_device *d,
978                     struct thandle *th)
979 {
980         struct osd_thread_info *oti = osd_oti_get(env);
981         struct osd_device  *dev = osd_dt_dev(d);
982         handle_t           *jh;
983         struct osd_thandle *oh;
984         int rc;
985
986         ENTRY;
987
988         LASSERT(current->journal_info == NULL);
989
990         oh = container_of0(th, struct osd_thandle, ot_super);
991         LASSERT(oh != NULL);
992         LASSERT(oh->ot_handle == NULL);
993
994         rc = dt_txn_hook_start(env, d, th);
995         if (rc != 0)
996                 GOTO(out, rc);
997
998         if (unlikely(osd_param_is_not_sane(dev, th))) {
999                 static unsigned long last_printed;
1000                 static int last_credits;
1001
1002                 CWARN("%.16s: too many transaction credits (%d > %d)\n",
1003                       LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name,
1004                       oh->ot_credits,
1005                       osd_journal(dev)->j_max_transaction_buffers);
1006                 CWARN("  create: %u/%u, delete: %u/%u, destroy: %u/%u\n",
1007                       oti->oti_declare_ops[OSD_OT_CREATE],
1008                       oti->oti_declare_ops_cred[OSD_OT_CREATE],
1009                       oti->oti_declare_ops[OSD_OT_DELETE],
1010                       oti->oti_declare_ops_cred[OSD_OT_DELETE],
1011                       oti->oti_declare_ops[OSD_OT_DESTROY],
1012                       oti->oti_declare_ops_cred[OSD_OT_DESTROY]);
1013                 CWARN("  attr_set: %u/%u, xattr_set: %u/%u\n",
1014                       oti->oti_declare_ops[OSD_OT_ATTR_SET],
1015                       oti->oti_declare_ops_cred[OSD_OT_ATTR_SET],
1016                       oti->oti_declare_ops[OSD_OT_XATTR_SET],
1017                       oti->oti_declare_ops_cred[OSD_OT_XATTR_SET]);
1018                 CWARN("  write: %u/%u, punch: %u/%u, quota %u/%u\n",
1019                       oti->oti_declare_ops[OSD_OT_WRITE],
1020                       oti->oti_declare_ops_cred[OSD_OT_WRITE],
1021                       oti->oti_declare_ops[OSD_OT_PUNCH],
1022                       oti->oti_declare_ops_cred[OSD_OT_PUNCH],
1023                       oti->oti_declare_ops[OSD_OT_QUOTA],
1024                       oti->oti_declare_ops_cred[OSD_OT_QUOTA]);
1025                 CWARN("  insert: %u/%u, delete: %u/%u\n",
1026                       oti->oti_declare_ops[OSD_OT_INSERT],
1027                       oti->oti_declare_ops_cred[OSD_OT_INSERT],
1028                       oti->oti_declare_ops[OSD_OT_DESTROY],
1029                       oti->oti_declare_ops_cred[OSD_OT_DESTROY]);
1030                 CWARN("  ref_add: %u/%u, ref_del: %u/%u\n",
1031                       oti->oti_declare_ops[OSD_OT_REF_ADD],
1032                       oti->oti_declare_ops_cred[OSD_OT_REF_ADD],
1033                       oti->oti_declare_ops[OSD_OT_REF_DEL],
1034                       oti->oti_declare_ops_cred[OSD_OT_REF_DEL]);
1035
1036                 if (last_credits != oh->ot_credits &&
1037                     time_after(jiffies, last_printed + 60 * HZ)) {
1038                         libcfs_debug_dumpstack(NULL);
1039                         last_credits = oh->ot_credits;
1040                         last_printed = jiffies;
1041                 }
1042                 /* XXX Limit the credits to 'max_transaction_buffers', and
1043                  *     let the underlying filesystem to catch the error if
1044                  *     we really need so many credits.
1045                  *
1046                  *     This should be removed when we can calculate the
1047                  *     credits precisely. */
1048                 oh->ot_credits = osd_journal(dev)->j_max_transaction_buffers;
1049         }
1050
1051         /*
1052          * XXX temporary stuff. Some abstraction layer should
1053          * be used.
1054          */
1055         jh = osd_journal_start_sb(osd_sb(dev), LDISKFS_HT_MISC, oh->ot_credits);
1056         osd_th_started(oh);
1057         if (!IS_ERR(jh)) {
1058                 oh->ot_handle = jh;
1059                 LASSERT(oti->oti_txns == 0);
1060                 lu_context_init(&th->th_ctx, th->th_tags);
1061                 lu_context_enter(&th->th_ctx);
1062
1063                 lu_device_get(&d->dd_lu_dev);
1064                 lu_ref_add_at(&d->dd_lu_dev.ld_reference, &oh->ot_dev_link,
1065                               "osd-tx", th);
1066                 oti->oti_txns++;
1067                 rc = 0;
1068         } else {
1069                 rc = PTR_ERR(jh);
1070         }
1071 out:
1072         RETURN(rc);
1073 }
1074
1075 static int osd_seq_exists(const struct lu_env *env,
1076                               struct osd_device *osd, obd_seq seq)
1077 {
1078         struct lu_seq_range     *range = &osd_oti_get(env)->oti_seq_range;
1079         struct seq_server_site  *ss = osd_seq_site(osd);
1080         int                     rc;
1081         ENTRY;
1082
1083         if (ss == NULL)
1084                 RETURN(1);
1085
1086         rc = osd_fld_lookup(env, osd, seq, range);
1087         if (rc != 0) {
1088                 if (rc != -ENOENT)
1089                         CERROR("%s: can't lookup FLD sequence "LPX64
1090                                ": rc = %d\n", osd_name(osd), seq, rc);
1091                 RETURN(0);
1092         }
1093
1094         RETURN(ss->ss_node_id == range->lsr_index);
1095 }
1096
1097 /*
1098  * Concurrency: shouldn't matter.
1099  */
1100 static int osd_trans_stop(const struct lu_env *env, struct thandle *th)
1101 {
1102         int                     rc = 0;
1103         struct osd_thandle     *oh;
1104         struct osd_thread_info *oti = osd_oti_get(env);
1105         struct osd_iobuf       *iobuf = &oti->oti_iobuf;
1106         struct qsd_instance    *qsd = oti->oti_dev->od_quota_slave;
1107         ENTRY;
1108
1109         oh = container_of0(th, struct osd_thandle, ot_super);
1110
1111         if (qsd != NULL)
1112                 /* inform the quota slave device that the transaction is
1113                  * stopping */
1114                 qsd_op_end(env, qsd, oh->ot_quota_trans);
1115         oh->ot_quota_trans = NULL;
1116
1117         if (oh->ot_handle != NULL) {
1118                 handle_t *hdl = oh->ot_handle;
1119
1120                 /*
1121                  * add commit callback
1122                  * notice we don't do this in osd_trans_start()
1123                  * as underlying transaction can change during truncate
1124                  */
1125                 ldiskfs_journal_callback_add(hdl, osd_trans_commit_cb,
1126                                          &oh->ot_jcb);
1127
1128                 LASSERT(oti->oti_txns == 1);
1129                 oti->oti_txns--;
1130                 rc = dt_txn_hook_stop(env, th);
1131                 if (rc != 0)
1132                         CERROR("Failure in transaction hook: %d\n", rc);
1133
1134                 /* hook functions might modify th_sync */
1135                 hdl->h_sync = th->th_sync;
1136
1137                 oh->ot_handle = NULL;
1138                 OSD_CHECK_SLOW_TH(oh, oti->oti_dev,
1139                                   rc = ldiskfs_journal_stop(hdl));
1140                 if (rc != 0)
1141                         CERROR("Failure to stop transaction: %d\n", rc);
1142         } else {
1143                 OBD_FREE_PTR(oh);
1144         }
1145
1146         /* as we want IO to journal and data IO be concurrent, we don't block
1147          * awaiting data IO completion in osd_do_bio(), instead we wait here
1148          * once transaction is submitted to the journal. all reqular requests
1149          * don't do direct IO (except read/write), thus this wait_event becomes
1150          * no-op for them.
1151          *
1152          * IMPORTANT: we have to wait till any IO submited by the thread is
1153          * completed otherwise iobuf may be corrupted by different request
1154          */
1155         wait_event(iobuf->dr_wait,
1156                        atomic_read(&iobuf->dr_numreqs) == 0);
1157         if (!rc)
1158                 rc = iobuf->dr_error;
1159
1160         RETURN(rc);
1161 }
1162
1163 static int osd_trans_cb_add(struct thandle *th, struct dt_txn_commit_cb *dcb)
1164 {
1165         struct osd_thandle *oh = container_of0(th, struct osd_thandle,
1166                                                ot_super);
1167
1168         LASSERT(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC);
1169         LASSERT(&dcb->dcb_func != NULL);
1170         cfs_list_add(&dcb->dcb_linkage, &oh->ot_dcb_list);
1171
1172         return 0;
1173 }
1174
1175 /*
1176  * Called just before object is freed. Releases all resources except for
1177  * object itself (that is released by osd_object_free()).
1178  *
1179  * Concurrency: no concurrent access is possible that late in object
1180  * life-cycle.
1181  */
1182 static void osd_object_delete(const struct lu_env *env, struct lu_object *l)
1183 {
1184         struct osd_object *obj   = osd_obj(l);
1185         struct inode      *inode = obj->oo_inode;
1186
1187         LINVRNT(osd_invariant(obj));
1188
1189         /*
1190          * If object is unlinked remove fid->ino mapping from object index.
1191          */
1192
1193         osd_index_fini(obj);
1194         if (inode != NULL) {
1195                 struct qsd_instance     *qsd = osd_obj2dev(obj)->od_quota_slave;
1196                 qid_t                    uid = inode->i_uid;
1197                 qid_t                    gid = inode->i_gid;
1198
1199                 iput(inode);
1200                 obj->oo_inode = NULL;
1201
1202                 if (qsd != NULL) {
1203                         struct osd_thread_info  *info = osd_oti_get(env);
1204                         struct lquota_id_info   *qi = &info->oti_qi;
1205
1206                         /* Release granted quota to master if necessary */
1207                         qi->lqi_id.qid_uid = uid;
1208                         qsd_op_adjust(env, qsd, &qi->lqi_id, USRQUOTA);
1209
1210                         qi->lqi_id.qid_uid = gid;
1211                         qsd_op_adjust(env, qsd, &qi->lqi_id, GRPQUOTA);
1212                 }
1213         }
1214 }
1215
1216 /*
1217  * Concurrency: ->loo_object_release() is called under site spin-lock.
1218  */
1219 static void osd_object_release(const struct lu_env *env,
1220                                struct lu_object *l)
1221 {
1222 }
1223
1224 /*
1225  * Concurrency: shouldn't matter.
1226  */
1227 static int osd_object_print(const struct lu_env *env, void *cookie,
1228                             lu_printer_t p, const struct lu_object *l)
1229 {
1230         struct osd_object *o = osd_obj(l);
1231         struct iam_descr  *d;
1232
1233         if (o->oo_dir != NULL)
1234                 d = o->oo_dir->od_container.ic_descr;
1235         else
1236                 d = NULL;
1237         return (*p)(env, cookie,
1238                     LUSTRE_OSD_LDISKFS_NAME"-object@%p(i:%p:%lu/%u)[%s]",
1239                     o, o->oo_inode,
1240                     o->oo_inode ? o->oo_inode->i_ino : 0UL,
1241                     o->oo_inode ? o->oo_inode->i_generation : 0,
1242                     d ? d->id_ops->id_name : "plain");
1243 }
1244
1245 /*
1246  * Concurrency: shouldn't matter.
1247  */
1248 int osd_statfs(const struct lu_env *env, struct dt_device *d,
1249                struct obd_statfs *sfs)
1250 {
1251         struct osd_device  *osd = osd_dt_dev(d);
1252         struct super_block *sb = osd_sb(osd);
1253         struct kstatfs     *ksfs;
1254         int result = 0;
1255
1256         if (unlikely(osd->od_mnt == NULL))
1257                 return -EINPROGRESS;
1258
1259         /* osd_lproc.c call this without env, allocate ksfs for that case */
1260         if (unlikely(env == NULL)) {
1261                 OBD_ALLOC_PTR(ksfs);
1262                 if (ksfs == NULL)
1263                         return -ENOMEM;
1264         } else {
1265                 ksfs = &osd_oti_get(env)->oti_ksfs;
1266         }
1267
1268         spin_lock(&osd->od_osfs_lock);
1269         /* cache 1 second */
1270         if (cfs_time_before_64(osd->od_osfs_age, cfs_time_shift_64(-1))) {
1271                 result = sb->s_op->statfs(sb->s_root, ksfs);
1272                 if (likely(result == 0)) { /* N.B. statfs can't really fail */
1273                         osd->od_osfs_age = cfs_time_current_64();
1274                         statfs_pack(&osd->od_statfs, ksfs);
1275                         if (sb->s_flags & MS_RDONLY)
1276                                 sfs->os_state = OS_STATE_READONLY;
1277                 }
1278         }
1279
1280         if (likely(result == 0))
1281                 *sfs = osd->od_statfs;
1282         spin_unlock(&osd->od_osfs_lock);
1283
1284         if (unlikely(env == NULL))
1285                 OBD_FREE_PTR(ksfs);
1286
1287         return result;
1288 }
1289
1290 /**
1291  * Estimate space needed for file creations. We assume the largest filename
1292  * which is 2^64 - 1, hence a filename of 20 chars.
1293  * This is 28 bytes per object which is 28MB for 1M objects ... no so bad.
1294  */
1295 #ifdef __LDISKFS_DIR_REC_LEN
1296 #define PER_OBJ_USAGE __LDISKFS_DIR_REC_LEN(20)
1297 #else
1298 #define PER_OBJ_USAGE LDISKFS_DIR_REC_LEN(20)
1299 #endif
1300
1301 /*
1302  * Concurrency: doesn't access mutable data.
1303  */
1304 static void osd_conf_get(const struct lu_env *env,
1305                          const struct dt_device *dev,
1306                          struct dt_device_param *param)
1307 {
1308         struct super_block *sb = osd_sb(osd_dt_dev(dev));
1309
1310         /*
1311          * XXX should be taken from not-yet-existing fs abstraction layer.
1312          */
1313         param->ddp_max_name_len = LDISKFS_NAME_LEN;
1314         param->ddp_max_nlink    = LDISKFS_LINK_MAX;
1315         param->ddp_block_shift  = sb->s_blocksize_bits;
1316         param->ddp_mount_type     = LDD_MT_LDISKFS;
1317         param->ddp_maxbytes       = sb->s_maxbytes;
1318         /* Overhead estimate should be fairly accurate, so we really take a tiny
1319          * error margin which also avoids fragmenting the filesystem too much */
1320         param->ddp_grant_reserved = 2; /* end up to be 1.9% after conversion */
1321         /* inode are statically allocated, so per-inode space consumption
1322          * is the space consumed by the directory entry */
1323         param->ddp_inodespace     = PER_OBJ_USAGE;
1324         /* per-fragment overhead to be used by the client code */
1325         param->ddp_grant_frag     = 6 * LDISKFS_BLOCK_SIZE(sb);
1326         param->ddp_mntopts      = 0;
1327         if (test_opt(sb, XATTR_USER))
1328                 param->ddp_mntopts |= MNTOPT_USERXATTR;
1329         if (test_opt(sb, POSIX_ACL))
1330                 param->ddp_mntopts |= MNTOPT_ACL;
1331
1332 #if defined(LDISKFS_FEATURE_INCOMPAT_EA_INODE)
1333         if (LDISKFS_HAS_INCOMPAT_FEATURE(sb, LDISKFS_FEATURE_INCOMPAT_EA_INODE))
1334                 param->ddp_max_ea_size = LDISKFS_XATTR_MAX_LARGE_EA_SIZE;
1335         else
1336 #endif
1337                 param->ddp_max_ea_size = sb->s_blocksize;
1338
1339 }
1340
1341 /*
1342  * Concurrency: shouldn't matter.
1343  */
1344 static int osd_sync(const struct lu_env *env, struct dt_device *d)
1345 {
1346         CDEBUG(D_HA, "syncing OSD %s\n", LUSTRE_OSD_LDISKFS_NAME);
1347         return ldiskfs_force_commit(osd_sb(osd_dt_dev(d)));
1348 }
1349
1350 /**
1351  * Start commit for OSD device.
1352  *
1353  * An implementation of dt_commit_async method for OSD device.
1354  * Asychronously starts underlayng fs sync and thereby a transaction
1355  * commit.
1356  *
1357  * \param env environment
1358  * \param d dt device
1359  *
1360  * \see dt_device_operations
1361  */
1362 static int osd_commit_async(const struct lu_env *env,
1363                             struct dt_device *d)
1364 {
1365         struct super_block *s = osd_sb(osd_dt_dev(d));
1366         ENTRY;
1367
1368         CDEBUG(D_HA, "async commit OSD %s\n", LUSTRE_OSD_LDISKFS_NAME);
1369         RETURN(s->s_op->sync_fs(s, 0));
1370 }
1371
1372 /*
1373  * Concurrency: shouldn't matter.
1374  */
1375
1376 static int osd_ro(const struct lu_env *env, struct dt_device *d)
1377 {
1378         struct super_block *sb = osd_sb(osd_dt_dev(d));
1379         struct block_device *dev = sb->s_bdev;
1380 #ifdef HAVE_DEV_SET_RDONLY
1381         struct block_device *jdev = LDISKFS_SB(sb)->journal_bdev;
1382         int rc = 0;
1383 #else
1384         int rc = -EOPNOTSUPP;
1385 #endif
1386         ENTRY;
1387
1388 #ifdef HAVE_DEV_SET_RDONLY
1389         CERROR("*** setting %s read-only ***\n", osd_dt_dev(d)->od_svname);
1390
1391         if (jdev && (jdev != dev)) {
1392                 CDEBUG(D_IOCTL | D_HA, "set journal dev %lx rdonly\n",
1393                        (long)jdev);
1394                 dev_set_rdonly(jdev);
1395         }
1396         CDEBUG(D_IOCTL | D_HA, "set dev %lx rdonly\n", (long)dev);
1397         dev_set_rdonly(dev);
1398 #else
1399         CERROR("%s: %lx CANNOT BE SET READONLY: rc = %d\n",
1400                osd_dt_dev(d)->od_svname, (long)dev, rc);
1401 #endif
1402         RETURN(rc);
1403 }
1404
1405 /*
1406  * Concurrency: serialization provided by callers.
1407  */
1408 static int osd_init_capa_ctxt(const struct lu_env *env, struct dt_device *d,
1409                               int mode, unsigned long timeout, __u32 alg,
1410                               struct lustre_capa_key *keys)
1411 {
1412         struct osd_device *dev = osd_dt_dev(d);
1413         ENTRY;
1414
1415         dev->od_fl_capa = mode;
1416         dev->od_capa_timeout = timeout;
1417         dev->od_capa_alg = alg;
1418         dev->od_capa_keys = keys;
1419         RETURN(0);
1420 }
1421
1422 /**
1423  * Note: we do not count into QUOTA here.
1424  * If we mount with --data_journal we may need more.
1425  */
1426 const int osd_dto_credits_noquota[DTO_NR] = {
1427         /**
1428          * Insert/Delete.
1429          * INDEX_EXTRA_TRANS_BLOCKS(8) +
1430          * SINGLEDATA_TRANS_BLOCKS(8)
1431          * XXX Note: maybe iam need more, since iam have more level than
1432          *           EXT3 htree.
1433          */
1434         [DTO_INDEX_INSERT]  = 16,
1435         [DTO_INDEX_DELETE]  = 16,
1436         /**
1437          * Used for OI scrub
1438          */
1439         [DTO_INDEX_UPDATE]  = 16,
1440         /**
1441          * Create a object. The same as create object in EXT3.
1442          * DATA_TRANS_BLOCKS(14) +
1443          * INDEX_EXTRA_BLOCKS(8) +
1444          * 3(inode bits, groups, GDT)
1445          */
1446         [DTO_OBJECT_CREATE] = 25,
1447         /**
1448          * XXX: real credits to be fixed
1449          */
1450         [DTO_OBJECT_DELETE] = 25,
1451         /**
1452          * Attr set credits (inode)
1453          */
1454         [DTO_ATTR_SET_BASE] = 1,
1455         /**
1456          * Xattr set. The same as xattr of EXT3.
1457          * DATA_TRANS_BLOCKS(14)
1458          * XXX Note: in original MDS implmentation INDEX_EXTRA_TRANS_BLOCKS
1459          * are also counted in. Do not know why?
1460          */
1461         [DTO_XATTR_SET]     = 14,
1462         [DTO_LOG_REC]       = 14,
1463         /**
1464          * credits for inode change during write.
1465          */
1466         [DTO_WRITE_BASE]    = 3,
1467         /**
1468          * credits for single block write.
1469          */
1470         [DTO_WRITE_BLOCK]   = 14,
1471         /**
1472          * Attr set credits for chown.
1473          * This is extra credits for setattr, and it is null without quota
1474          */
1475         [DTO_ATTR_SET_CHOWN]= 0
1476 };
1477
1478 static const struct dt_device_operations osd_dt_ops = {
1479         .dt_root_get       = osd_root_get,
1480         .dt_statfs         = osd_statfs,
1481         .dt_trans_create   = osd_trans_create,
1482         .dt_trans_start    = osd_trans_start,
1483         .dt_trans_stop     = osd_trans_stop,
1484         .dt_trans_cb_add   = osd_trans_cb_add,
1485         .dt_conf_get       = osd_conf_get,
1486         .dt_sync           = osd_sync,
1487         .dt_ro             = osd_ro,
1488         .dt_commit_async   = osd_commit_async,
1489         .dt_init_capa_ctxt = osd_init_capa_ctxt,
1490 };
1491
1492 static void osd_object_read_lock(const struct lu_env *env,
1493                                  struct dt_object *dt, unsigned role)
1494 {
1495         struct osd_object *obj = osd_dt_obj(dt);
1496         struct osd_thread_info *oti = osd_oti_get(env);
1497
1498         LINVRNT(osd_invariant(obj));
1499
1500         LASSERT(obj->oo_owner != env);
1501         down_read_nested(&obj->oo_sem, role);
1502
1503         LASSERT(obj->oo_owner == NULL);
1504         oti->oti_r_locks++;
1505 }
1506
1507 static void osd_object_write_lock(const struct lu_env *env,
1508                                   struct dt_object *dt, unsigned role)
1509 {
1510         struct osd_object *obj = osd_dt_obj(dt);
1511         struct osd_thread_info *oti = osd_oti_get(env);
1512
1513         LINVRNT(osd_invariant(obj));
1514
1515         LASSERT(obj->oo_owner != env);
1516         down_write_nested(&obj->oo_sem, role);
1517
1518         LASSERT(obj->oo_owner == NULL);
1519         obj->oo_owner = env;
1520         oti->oti_w_locks++;
1521 }
1522
1523 static void osd_object_read_unlock(const struct lu_env *env,
1524                                    struct dt_object *dt)
1525 {
1526         struct osd_object *obj = osd_dt_obj(dt);
1527         struct osd_thread_info *oti = osd_oti_get(env);
1528
1529         LINVRNT(osd_invariant(obj));
1530
1531         LASSERT(oti->oti_r_locks > 0);
1532         oti->oti_r_locks--;
1533         up_read(&obj->oo_sem);
1534 }
1535
1536 static void osd_object_write_unlock(const struct lu_env *env,
1537                                     struct dt_object *dt)
1538 {
1539         struct osd_object *obj = osd_dt_obj(dt);
1540         struct osd_thread_info *oti = osd_oti_get(env);
1541
1542         LINVRNT(osd_invariant(obj));
1543
1544         LASSERT(obj->oo_owner == env);
1545         LASSERT(oti->oti_w_locks > 0);
1546         oti->oti_w_locks--;
1547         obj->oo_owner = NULL;
1548         up_write(&obj->oo_sem);
1549 }
1550
1551 static int osd_object_write_locked(const struct lu_env *env,
1552                                    struct dt_object *dt)
1553 {
1554         struct osd_object *obj = osd_dt_obj(dt);
1555
1556         LINVRNT(osd_invariant(obj));
1557
1558         return obj->oo_owner == env;
1559 }
1560
1561 static int capa_is_sane(const struct lu_env *env,
1562                         struct osd_device *dev,
1563                         struct lustre_capa *capa,
1564                         struct lustre_capa_key *keys)
1565 {
1566         struct osd_thread_info *oti = osd_oti_get(env);
1567         struct lustre_capa *tcapa = &oti->oti_capa;
1568         struct obd_capa *oc;
1569         int i, rc = 0;
1570         ENTRY;
1571
1572         oc = capa_lookup(dev->od_capa_hash, capa, 0);
1573         if (oc) {
1574                 if (capa_is_expired(oc)) {
1575                         DEBUG_CAPA(D_ERROR, capa, "expired");
1576                         rc = -ESTALE;
1577                 }
1578                 capa_put(oc);
1579                 RETURN(rc);
1580         }
1581
1582         if (capa_is_expired_sec(capa)) {
1583                 DEBUG_CAPA(D_ERROR, capa, "expired");
1584                 RETURN(-ESTALE);
1585         }
1586
1587         spin_lock(&capa_lock);
1588         for (i = 0; i < 2; i++) {
1589                 if (keys[i].lk_keyid == capa->lc_keyid) {
1590                         oti->oti_capa_key = keys[i];
1591                         break;
1592                 }
1593         }
1594         spin_unlock(&capa_lock);
1595
1596         if (i == 2) {
1597                 DEBUG_CAPA(D_ERROR, capa, "no matched capa key");
1598                 RETURN(-ESTALE);
1599         }
1600
1601         rc = capa_hmac(tcapa->lc_hmac, capa, oti->oti_capa_key.lk_key);
1602         if (rc)
1603                 RETURN(rc);
1604
1605         if (memcmp(tcapa->lc_hmac, capa->lc_hmac, sizeof(capa->lc_hmac))) {
1606                 DEBUG_CAPA(D_ERROR, capa, "HMAC mismatch");
1607                 RETURN(-EACCES);
1608         }
1609
1610         oc = capa_add(dev->od_capa_hash, capa);
1611         capa_put(oc);
1612
1613         RETURN(0);
1614 }
1615
1616 int osd_object_auth(const struct lu_env *env, struct dt_object *dt,
1617                     struct lustre_capa *capa, __u64 opc)
1618 {
1619         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
1620         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
1621         struct lu_capainfo *lci;
1622         int rc;
1623
1624         if (!osd->od_fl_capa)
1625                 return 0;
1626
1627         if (capa == BYPASS_CAPA)
1628                 return 0;
1629
1630         lci = lu_capainfo_get(env);
1631         if (unlikely(lci == NULL))
1632                 return 0;
1633
1634         if (lci->lci_auth == LC_ID_NONE)
1635                 return 0;
1636
1637         if (capa == NULL) {
1638                 CERROR("%s: no capability provided for FID "DFID": rc = %d\n",
1639                        osd_name(osd), PFID(fid), -EACCES);
1640                 return -EACCES;
1641         }
1642
1643         if (!lu_fid_eq(fid, &capa->lc_fid)) {
1644                 DEBUG_CAPA(D_ERROR, capa, "fid "DFID" mismatch with",
1645                            PFID(fid));
1646                 return -EACCES;
1647         }
1648
1649         if (!capa_opc_supported(capa, opc)) {
1650                 DEBUG_CAPA(D_ERROR, capa, "opc "LPX64" not supported by", opc);
1651                 return -EACCES;
1652         }
1653
1654         rc = capa_is_sane(env, osd, capa, osd->od_capa_keys);
1655         if (rc != 0) {
1656                 DEBUG_CAPA(D_ERROR, capa, "insane: rc = %d", rc);
1657                 return -EACCES;
1658         }
1659
1660         return 0;
1661 }
1662
1663 static struct timespec *osd_inode_time(const struct lu_env *env,
1664                                        struct inode *inode, __u64 seconds)
1665 {
1666         struct osd_thread_info  *oti = osd_oti_get(env);
1667         struct timespec         *t   = &oti->oti_time;
1668
1669         t->tv_sec = seconds;
1670         t->tv_nsec = 0;
1671         *t = timespec_trunc(*t, inode->i_sb->s_time_gran);
1672         return t;
1673 }
1674
1675
1676 static void osd_inode_getattr(const struct lu_env *env,
1677                               struct inode *inode, struct lu_attr *attr)
1678 {
1679         attr->la_valid      |= LA_ATIME | LA_MTIME | LA_CTIME | LA_MODE |
1680                                LA_SIZE | LA_BLOCKS | LA_UID | LA_GID |
1681                                LA_FLAGS | LA_NLINK | LA_RDEV | LA_BLKSIZE |
1682                                LA_TYPE;
1683
1684         attr->la_atime      = LTIME_S(inode->i_atime);
1685         attr->la_mtime      = LTIME_S(inode->i_mtime);
1686         attr->la_ctime      = LTIME_S(inode->i_ctime);
1687         attr->la_mode       = inode->i_mode;
1688         attr->la_size       = i_size_read(inode);
1689         attr->la_blocks     = inode->i_blocks;
1690         attr->la_uid        = inode->i_uid;
1691         attr->la_gid        = inode->i_gid;
1692         attr->la_flags      = LDISKFS_I(inode)->i_flags;
1693         attr->la_nlink      = inode->i_nlink;
1694         attr->la_rdev       = inode->i_rdev;
1695         attr->la_blksize    = 1 << inode->i_blkbits;
1696         attr->la_blkbits    = inode->i_blkbits;
1697 }
1698
1699 static int osd_attr_get(const struct lu_env *env,
1700                         struct dt_object *dt,
1701                         struct lu_attr *attr,
1702                         struct lustre_capa *capa)
1703 {
1704         struct osd_object *obj = osd_dt_obj(dt);
1705
1706         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
1707         LINVRNT(osd_invariant(obj));
1708
1709         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
1710                 return -EACCES;
1711
1712         spin_lock(&obj->oo_guard);
1713         osd_inode_getattr(env, obj->oo_inode, attr);
1714         spin_unlock(&obj->oo_guard);
1715         return 0;
1716 }
1717
1718 static int osd_declare_attr_set(const struct lu_env *env,
1719                                 struct dt_object *dt,
1720                                 const struct lu_attr *attr,
1721                                 struct thandle *handle)
1722 {
1723         struct osd_thandle     *oh;
1724         struct osd_object      *obj;
1725         struct osd_thread_info *info = osd_oti_get(env);
1726         struct lquota_id_info  *qi = &info->oti_qi;
1727         long long               bspace;
1728         int                     rc = 0;
1729         bool                    allocated;
1730         ENTRY;
1731
1732         LASSERT(dt != NULL);
1733         LASSERT(handle != NULL);
1734
1735         obj = osd_dt_obj(dt);
1736         LASSERT(osd_invariant(obj));
1737
1738         oh = container_of0(handle, struct osd_thandle, ot_super);
1739         LASSERT(oh->ot_handle == NULL);
1740
1741         osd_trans_declare_op(env, oh, OSD_OT_ATTR_SET,
1742                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
1743
1744         if (attr == NULL || obj->oo_inode == NULL)
1745                 RETURN(rc);
1746
1747         bspace   = obj->oo_inode->i_blocks;
1748         bspace <<= obj->oo_inode->i_sb->s_blocksize_bits;
1749         bspace   = toqb(bspace);
1750
1751         /* Changing ownership is always preformed by super user, it should not
1752          * fail with EDQUOT.
1753          *
1754          * We still need to call the osd_declare_qid() to calculate the journal
1755          * credits for updating quota accounting files and to trigger quota
1756          * space adjustment once the operation is completed.*/
1757         if ((attr->la_valid & LA_UID) != 0 &&
1758              attr->la_uid != obj->oo_inode->i_uid) {
1759                 qi->lqi_type = USRQUOTA;
1760
1761                 /* inode accounting */
1762                 qi->lqi_is_blk = false;
1763
1764                 /* one more inode for the new owner ... */
1765                 qi->lqi_id.qid_uid = attr->la_uid;
1766                 qi->lqi_space      = 1;
1767                 allocated = (attr->la_uid == 0) ? true : false;
1768                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1769                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1770                         rc = 0;
1771                 if (rc)
1772                         RETURN(rc);
1773
1774                 /* and one less inode for the current uid */
1775                 qi->lqi_id.qid_uid = obj->oo_inode->i_uid;
1776                 qi->lqi_space      = -1;
1777                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1778                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1779                         rc = 0;
1780                 if (rc)
1781                         RETURN(rc);
1782
1783                 /* block accounting */
1784                 qi->lqi_is_blk = true;
1785
1786                 /* more blocks for the new owner ... */
1787                 qi->lqi_id.qid_uid = attr->la_uid;
1788                 qi->lqi_space      = bspace;
1789                 allocated = (attr->la_uid == 0) ? true : false;
1790                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1791                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1792                         rc = 0;
1793                 if (rc)
1794                         RETURN(rc);
1795
1796                 /* and finally less blocks for the current owner */
1797                 qi->lqi_id.qid_uid = obj->oo_inode->i_uid;
1798                 qi->lqi_space      = -bspace;
1799                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1800                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1801                         rc = 0;
1802                 if (rc)
1803                         RETURN(rc);
1804         }
1805
1806         if (attr->la_valid & LA_GID &&
1807             attr->la_gid != obj->oo_inode->i_gid) {
1808                 qi->lqi_type = GRPQUOTA;
1809
1810                 /* inode accounting */
1811                 qi->lqi_is_blk = false;
1812
1813                 /* one more inode for the new group owner ... */
1814                 qi->lqi_id.qid_gid = attr->la_gid;
1815                 qi->lqi_space      = 1;
1816                 allocated = (attr->la_gid == 0) ? true : false;
1817                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1818                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1819                         rc = 0;
1820                 if (rc)
1821                         RETURN(rc);
1822
1823                 /* and one less inode for the current gid */
1824                 qi->lqi_id.qid_gid = obj->oo_inode->i_gid;
1825                 qi->lqi_space      = -1;
1826                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1827                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1828                         rc = 0;
1829                 if (rc)
1830                         RETURN(rc);
1831
1832                 /* block accounting */
1833                 qi->lqi_is_blk = true;
1834
1835                 /* more blocks for the new owner ... */
1836                 qi->lqi_id.qid_gid = attr->la_gid;
1837                 qi->lqi_space      = bspace;
1838                 allocated = (attr->la_gid == 0) ? true : false;
1839                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1840                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1841                         rc = 0;
1842                 if (rc)
1843                         RETURN(rc);
1844
1845                 /* and finally less blocks for the current owner */
1846                 qi->lqi_id.qid_gid = obj->oo_inode->i_gid;
1847                 qi->lqi_space      = -bspace;
1848                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1849                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1850                         rc = 0;
1851                 if (rc)
1852                         RETURN(rc);
1853         }
1854
1855         RETURN(rc);
1856 }
1857
1858 static int osd_inode_setattr(const struct lu_env *env,
1859                              struct inode *inode, const struct lu_attr *attr)
1860 {
1861         __u64 bits;
1862
1863         bits = attr->la_valid;
1864
1865         if (bits & LA_ATIME)
1866                 inode->i_atime  = *osd_inode_time(env, inode, attr->la_atime);
1867         if (bits & LA_CTIME)
1868                 inode->i_ctime  = *osd_inode_time(env, inode, attr->la_ctime);
1869         if (bits & LA_MTIME)
1870                 inode->i_mtime  = *osd_inode_time(env, inode, attr->la_mtime);
1871         if (bits & LA_SIZE) {
1872                 LDISKFS_I(inode)->i_disksize = attr->la_size;
1873                 i_size_write(inode, attr->la_size);
1874         }
1875
1876 #if 0
1877         /* OSD should not change "i_blocks" which is used by quota.
1878          * "i_blocks" should be changed by ldiskfs only. */
1879         if (bits & LA_BLOCKS)
1880                 inode->i_blocks = attr->la_blocks;
1881 #endif
1882         if (bits & LA_MODE)
1883                 inode->i_mode   = (inode->i_mode & S_IFMT) |
1884                         (attr->la_mode & ~S_IFMT);
1885         if (bits & LA_UID)
1886                 inode->i_uid    = attr->la_uid;
1887         if (bits & LA_GID)
1888                 inode->i_gid    = attr->la_gid;
1889         if (bits & LA_NLINK)
1890                 set_nlink(inode, attr->la_nlink);
1891         if (bits & LA_RDEV)
1892                 inode->i_rdev   = attr->la_rdev;
1893
1894         if (bits & LA_FLAGS) {
1895                 /* always keep S_NOCMTIME */
1896                 inode->i_flags = ll_ext_to_inode_flags(attr->la_flags) |
1897                                  S_NOCMTIME;
1898         }
1899         return 0;
1900 }
1901
1902 static int osd_quota_transfer(struct inode *inode, const struct lu_attr *attr)
1903 {
1904         if ((attr->la_valid & LA_UID && attr->la_uid != inode->i_uid) ||
1905             (attr->la_valid & LA_GID && attr->la_gid != inode->i_gid)) {
1906                 struct iattr    iattr;
1907                 int             rc;
1908
1909                 iattr.ia_valid = 0;
1910                 if (attr->la_valid & LA_UID)
1911                         iattr.ia_valid |= ATTR_UID;
1912                 if (attr->la_valid & LA_GID)
1913                         iattr.ia_valid |= ATTR_GID;
1914                 iattr.ia_uid = attr->la_uid;
1915                 iattr.ia_gid = attr->la_gid;
1916
1917                 rc = ll_vfs_dq_transfer(inode, &iattr);
1918                 if (rc) {
1919                         CERROR("%s: quota transfer failed: rc = %d. Is quota "
1920                                "enforcement enabled on the ldiskfs filesystem?",
1921                                inode->i_sb->s_id, rc);
1922                         return rc;
1923                 }
1924         }
1925         return 0;
1926 }
1927
1928 static int osd_attr_set(const struct lu_env *env,
1929                         struct dt_object *dt,
1930                         const struct lu_attr *attr,
1931                         struct thandle *handle,
1932                         struct lustre_capa *capa)
1933 {
1934         struct osd_object *obj = osd_dt_obj(dt);
1935         struct inode      *inode;
1936         int rc;
1937
1938         LASSERT(handle != NULL);
1939         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
1940         LASSERT(osd_invariant(obj));
1941
1942         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
1943                 return -EACCES;
1944
1945         osd_trans_exec_op(env, handle, OSD_OT_ATTR_SET);
1946
1947         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_FID_MAPPING)) {
1948                 struct osd_thread_info  *oti  = osd_oti_get(env);
1949                 const struct lu_fid     *fid0 = lu_object_fid(&dt->do_lu);
1950                 struct lu_fid           *fid1 = &oti->oti_fid;
1951                 struct osd_inode_id     *id   = &oti->oti_id;
1952                 struct iam_path_descr   *ipd;
1953                 struct iam_container    *bag;
1954                 struct osd_thandle      *oh;
1955                 int                      rc;
1956
1957                 fid_cpu_to_be(fid1, fid0);
1958                 memset(id, 1, sizeof(*id));
1959                 bag = &osd_fid2oi(osd_dev(dt->do_lu.lo_dev),
1960                                   fid0)->oi_dir.od_container;
1961                 ipd = osd_idx_ipd_get(env, bag);
1962                 if (unlikely(ipd == NULL))
1963                         RETURN(-ENOMEM);
1964
1965                 oh = container_of0(handle, struct osd_thandle, ot_super);
1966                 rc = iam_update(oh->ot_handle, bag, (const struct iam_key *)fid1,
1967                                 (const struct iam_rec *)id, ipd);
1968                 osd_ipd_put(env, bag, ipd);
1969                 return(rc > 0 ? 0 : rc);
1970         }
1971
1972         inode = obj->oo_inode;
1973         ll_vfs_dq_init(inode);
1974
1975         rc = osd_quota_transfer(inode, attr);
1976         if (rc)
1977                 return rc;
1978
1979         spin_lock(&obj->oo_guard);
1980         rc = osd_inode_setattr(env, inode, attr);
1981         spin_unlock(&obj->oo_guard);
1982
1983         if (!rc)
1984                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
1985         return rc;
1986 }
1987
1988 struct dentry *osd_child_dentry_get(const struct lu_env *env,
1989                                     struct osd_object *obj,
1990                                     const char *name, const int namelen)
1991 {
1992         return osd_child_dentry_by_inode(env, obj->oo_inode, name, namelen);
1993 }
1994
1995 static int osd_mkfile(struct osd_thread_info *info, struct osd_object *obj,
1996                       umode_t mode, struct dt_allocation_hint *hint,
1997                       struct thandle *th)
1998 {
1999         int result;
2000         struct osd_device  *osd = osd_obj2dev(obj);
2001         struct osd_thandle *oth;
2002         struct dt_object   *parent = NULL;
2003         struct inode       *inode;
2004
2005         LINVRNT(osd_invariant(obj));
2006         LASSERT(obj->oo_inode == NULL);
2007         LASSERT(obj->oo_hl_head == NULL);
2008
2009         if (S_ISDIR(mode) && ldiskfs_pdo) {
2010                 obj->oo_hl_head =ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
2011                 if (obj->oo_hl_head == NULL)
2012                         return -ENOMEM;
2013         }
2014
2015         oth = container_of(th, struct osd_thandle, ot_super);
2016         LASSERT(oth->ot_handle->h_transaction != NULL);
2017
2018         if (hint && hint->dah_parent)
2019                 parent = hint->dah_parent;
2020
2021         inode = ldiskfs_create_inode(oth->ot_handle,
2022                                      parent ? osd_dt_obj(parent)->oo_inode :
2023                                               osd_sb(osd)->s_root->d_inode,
2024                                      mode);
2025         if (!IS_ERR(inode)) {
2026                 /* Do not update file c/mtime in ldiskfs.
2027                  * NB: don't need any lock because no contention at this
2028                  * early stage */
2029                 inode->i_flags |= S_NOCMTIME;
2030
2031                 /* For new created object, it must be consistent,
2032                  * and it is unnecessary to scrub against it. */
2033                 ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
2034                 obj->oo_inode = inode;
2035                 result = 0;
2036         } else {
2037                 if (obj->oo_hl_head != NULL) {
2038                         ldiskfs_htree_lock_head_free(obj->oo_hl_head);
2039                         obj->oo_hl_head = NULL;
2040                 }
2041                 result = PTR_ERR(inode);
2042         }
2043         LINVRNT(osd_invariant(obj));
2044         return result;
2045 }
2046
2047 enum {
2048         OSD_NAME_LEN = 255
2049 };
2050
2051 static int osd_mkdir(struct osd_thread_info *info, struct osd_object *obj,
2052                      struct lu_attr *attr,
2053                      struct dt_allocation_hint *hint,
2054                      struct dt_object_format *dof,
2055                      struct thandle *th)
2056 {
2057         int result;
2058         struct osd_thandle *oth;
2059         __u32 mode = (attr->la_mode & (S_IFMT | S_IRWXUGO | S_ISVTX));
2060
2061         LASSERT(S_ISDIR(attr->la_mode));
2062
2063         oth = container_of(th, struct osd_thandle, ot_super);
2064         LASSERT(oth->ot_handle->h_transaction != NULL);
2065         result = osd_mkfile(info, obj, mode, hint, th);
2066
2067         return result;
2068 }
2069
2070 static int osd_mk_index(struct osd_thread_info *info, struct osd_object *obj,
2071                         struct lu_attr *attr,
2072                         struct dt_allocation_hint *hint,
2073                         struct dt_object_format *dof,
2074                         struct thandle *th)
2075 {
2076         int result;
2077         struct osd_thandle *oth;
2078         const struct dt_index_features *feat = dof->u.dof_idx.di_feat;
2079
2080         __u32 mode = (attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX));
2081
2082         LASSERT(S_ISREG(attr->la_mode));
2083
2084         oth = container_of(th, struct osd_thandle, ot_super);
2085         LASSERT(oth->ot_handle->h_transaction != NULL);
2086
2087         result = osd_mkfile(info, obj, mode, hint, th);
2088         if (result == 0) {
2089                 LASSERT(obj->oo_inode != NULL);
2090                 if (feat->dif_flags & DT_IND_VARKEY)
2091                         result = iam_lvar_create(obj->oo_inode,
2092                                                  feat->dif_keysize_max,
2093                                                  feat->dif_ptrsize,
2094                                                  feat->dif_recsize_max,
2095                                                  oth->ot_handle);
2096                 else
2097                         result = iam_lfix_create(obj->oo_inode,
2098                                                  feat->dif_keysize_max,
2099                                                  feat->dif_ptrsize,
2100                                                  feat->dif_recsize_max,
2101                                                  oth->ot_handle);
2102
2103         }
2104         return result;
2105 }
2106
2107 static int osd_mkreg(struct osd_thread_info *info, struct osd_object *obj,
2108                      struct lu_attr *attr,
2109                      struct dt_allocation_hint *hint,
2110                      struct dt_object_format *dof,
2111                      struct thandle *th)
2112 {
2113         LASSERT(S_ISREG(attr->la_mode));
2114         return osd_mkfile(info, obj, (attr->la_mode &
2115                                (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
2116 }
2117
2118 static int osd_mksym(struct osd_thread_info *info, struct osd_object *obj,
2119                      struct lu_attr *attr,
2120                      struct dt_allocation_hint *hint,
2121                      struct dt_object_format *dof,
2122                      struct thandle *th)
2123 {
2124         LASSERT(S_ISLNK(attr->la_mode));
2125         return osd_mkfile(info, obj, (attr->la_mode &
2126                               (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
2127 }
2128
2129 static int osd_mknod(struct osd_thread_info *info, struct osd_object *obj,
2130                      struct lu_attr *attr,
2131                      struct dt_allocation_hint *hint,
2132                      struct dt_object_format *dof,
2133                      struct thandle *th)
2134 {
2135         umode_t mode = attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX);
2136         int result;
2137
2138         LINVRNT(osd_invariant(obj));
2139         LASSERT(obj->oo_inode == NULL);
2140         LASSERT(S_ISCHR(mode) || S_ISBLK(mode) ||
2141                 S_ISFIFO(mode) || S_ISSOCK(mode));
2142
2143         result = osd_mkfile(info, obj, mode, hint, th);
2144         if (result == 0) {
2145                 LASSERT(obj->oo_inode != NULL);
2146                 /*
2147                  * This inode should be marked dirty for i_rdev.  Currently
2148                  * that is done in the osd_attr_init().
2149                  */
2150                 init_special_inode(obj->oo_inode, obj->oo_inode->i_mode,
2151                                    attr->la_rdev);
2152         }
2153         LINVRNT(osd_invariant(obj));
2154         return result;
2155 }
2156
2157 typedef int (*osd_obj_type_f)(struct osd_thread_info *, struct osd_object *,
2158                               struct lu_attr *,
2159                               struct dt_allocation_hint *hint,
2160                               struct dt_object_format *dof,
2161                               struct thandle *);
2162
2163 static osd_obj_type_f osd_create_type_f(enum dt_format_type type)
2164 {
2165         osd_obj_type_f result;
2166
2167         switch (type) {
2168         case DFT_DIR:
2169                 result = osd_mkdir;
2170                 break;
2171         case DFT_REGULAR:
2172                 result = osd_mkreg;
2173                 break;
2174         case DFT_SYM:
2175                 result = osd_mksym;
2176                 break;
2177         case DFT_NODE:
2178                 result = osd_mknod;
2179                 break;
2180         case DFT_INDEX:
2181                 result = osd_mk_index;
2182                 break;
2183
2184         default:
2185                 LBUG();
2186                 break;
2187         }
2188         return result;
2189 }
2190
2191
2192 static void osd_ah_init(const struct lu_env *env, struct dt_allocation_hint *ah,
2193                         struct dt_object *parent, struct dt_object *child,
2194                         umode_t child_mode)
2195 {
2196         LASSERT(ah);
2197
2198         memset(ah, 0, sizeof(*ah));
2199         ah->dah_parent = parent;
2200         ah->dah_mode = child_mode;
2201 }
2202
2203 static void osd_attr_init(struct osd_thread_info *info, struct osd_object *obj,
2204                           struct lu_attr *attr, struct dt_object_format *dof)
2205 {
2206         struct inode   *inode = obj->oo_inode;
2207         __u64           valid = attr->la_valid;
2208         int             result;
2209
2210         attr->la_valid &= ~(LA_TYPE | LA_MODE);
2211
2212         if (dof->dof_type != DFT_NODE)
2213                 attr->la_valid &= ~LA_RDEV;
2214         if ((valid & LA_ATIME) && (attr->la_atime == LTIME_S(inode->i_atime)))
2215                 attr->la_valid &= ~LA_ATIME;
2216         if ((valid & LA_CTIME) && (attr->la_ctime == LTIME_S(inode->i_ctime)))
2217                 attr->la_valid &= ~LA_CTIME;
2218         if ((valid & LA_MTIME) && (attr->la_mtime == LTIME_S(inode->i_mtime)))
2219                 attr->la_valid &= ~LA_MTIME;
2220
2221         result = osd_quota_transfer(inode, attr);
2222         if (result)
2223                 return;
2224
2225         if (attr->la_valid != 0) {
2226                 result = osd_inode_setattr(info->oti_env, inode, attr);
2227                 /*
2228                  * The osd_inode_setattr() should always succeed here.  The
2229                  * only error that could be returned is EDQUOT when we are
2230                  * trying to change the UID or GID of the inode. However, this
2231                  * should not happen since quota enforcement is no longer
2232                  * enabled on ldiskfs (lquota takes care of it).
2233                  */
2234                 LASSERTF(result == 0, "%d", result);
2235                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2236         }
2237
2238         attr->la_valid = valid;
2239 }
2240
2241 /**
2242  * Helper function for osd_object_create()
2243  *
2244  * \retval 0, on success
2245  */
2246 static int __osd_object_create(struct osd_thread_info *info,
2247                                struct osd_object *obj, struct lu_attr *attr,
2248                                struct dt_allocation_hint *hint,
2249                                struct dt_object_format *dof,
2250                                struct thandle *th)
2251 {
2252         int     result;
2253         __u32   umask;
2254
2255         /* we drop umask so that permissions we pass are not affected */
2256         umask = current->fs->umask;
2257         current->fs->umask = 0;
2258
2259         result = osd_create_type_f(dof->dof_type)(info, obj, attr, hint, dof,
2260                                                   th);
2261         if (result == 0) {
2262                 osd_attr_init(info, obj, attr, dof);
2263                 osd_object_init0(obj);
2264                 /* bz 24037 */
2265                 if (obj->oo_inode && (obj->oo_inode->i_state & I_NEW))
2266                         unlock_new_inode(obj->oo_inode);
2267         }
2268
2269         /* restore previous umask value */
2270         current->fs->umask = umask;
2271
2272         return result;
2273 }
2274
2275 /**
2276  * Helper function for osd_object_create()
2277  *
2278  * \retval 0, on success
2279  */
2280 static int __osd_oi_insert(const struct lu_env *env, struct osd_object *obj,
2281                            const struct lu_fid *fid, struct thandle *th)
2282 {
2283         struct osd_thread_info *info = osd_oti_get(env);
2284         struct osd_inode_id    *id   = &info->oti_id;
2285         struct osd_device      *osd  = osd_obj2dev(obj);
2286         struct osd_thandle     *oh;
2287
2288         LASSERT(obj->oo_inode != NULL);
2289
2290         oh = container_of0(th, struct osd_thandle, ot_super);
2291         LASSERT(oh->ot_handle);
2292
2293         osd_id_gen(id, obj->oo_inode->i_ino, obj->oo_inode->i_generation);
2294         return osd_oi_insert(info, osd, fid, id, oh->ot_handle, OI_CHECK_FLD);
2295 }
2296
2297 int osd_fld_lookup(const struct lu_env *env, struct osd_device *osd,
2298                    obd_seq seq, struct lu_seq_range *range)
2299 {
2300         struct seq_server_site  *ss = osd_seq_site(osd);
2301
2302         if (fid_seq_is_idif(seq)) {
2303                 fld_range_set_ost(range);
2304                 range->lsr_index = idif_ost_idx(seq);
2305                 return 0;
2306         }
2307
2308         if (!fid_seq_in_fldb(seq)) {
2309                 fld_range_set_mdt(range);
2310                 if (ss != NULL)
2311                         /* FIXME: If ss is NULL, it suppose not get lsr_index
2312                          * at all */
2313                         range->lsr_index = ss->ss_node_id;
2314                 return 0;
2315         }
2316
2317         LASSERT(ss != NULL);
2318         fld_range_set_any(range);
2319         /* OSD will only do local fld lookup */
2320         return fld_local_lookup(env, ss->ss_server_fld, seq, range);
2321 }
2322
2323 /*
2324  * Concurrency: no external locking is necessary.
2325  */
2326 static int osd_declare_object_create(const struct lu_env *env,
2327                                      struct dt_object *dt,
2328                                      struct lu_attr *attr,
2329                                      struct dt_allocation_hint *hint,
2330                                      struct dt_object_format *dof,
2331                                      struct thandle *handle)
2332 {
2333         struct osd_thandle      *oh;
2334         int                      rc;
2335         ENTRY;
2336
2337         LASSERT(handle != NULL);
2338
2339         oh = container_of0(handle, struct osd_thandle, ot_super);
2340         LASSERT(oh->ot_handle == NULL);
2341
2342         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
2343                              osd_dto_credits_noquota[DTO_OBJECT_CREATE]);
2344         if (!fid_is_on_ost(osd_oti_get(env), osd_dt_dev(handle->th_dev),
2345                            lu_object_fid(&dt->do_lu), OI_CHECK_FLD))
2346                 /* Reuse idle OI block may cause additional one OI block
2347                  * to be changed. */
2348                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
2349                                 osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
2350
2351         /* If this is directory, then we expect . and .. to be inserted as
2352          * well. The one directory block always needs to be created for the
2353          * directory, so we could use DTO_WRITE_BASE here (GDT, block bitmap,
2354          * block), there is no danger of needing a tree for the first block.
2355          */
2356         if (attr && S_ISDIR(attr->la_mode)) {
2357                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
2358                                      osd_dto_credits_noquota[DTO_WRITE_BASE]);
2359                 osd_trans_declare_op(env, oh, OSD_OT_INSERT, 0);
2360         }
2361
2362         if (!attr)
2363                 RETURN(0);
2364
2365         rc = osd_declare_inode_qid(env, attr->la_uid, attr->la_gid, 1, oh,
2366                                    false, false, NULL, false);
2367         if (rc != 0)
2368                 RETURN(rc);
2369
2370         RETURN(rc);
2371 }
2372
2373 static int osd_object_create(const struct lu_env *env, struct dt_object *dt,
2374                              struct lu_attr *attr,
2375                              struct dt_allocation_hint *hint,
2376                              struct dt_object_format *dof,
2377                              struct thandle *th)
2378 {
2379         const struct lu_fid    *fid    = lu_object_fid(&dt->do_lu);
2380         struct osd_object      *obj    = osd_dt_obj(dt);
2381         struct osd_thread_info *info   = osd_oti_get(env);
2382         int result;
2383
2384         ENTRY;
2385
2386         LINVRNT(osd_invariant(obj));
2387         LASSERT(!dt_object_exists(dt) && !dt_object_remote(dt));
2388         LASSERT(osd_write_locked(env, obj));
2389         LASSERT(th != NULL);
2390
2391         if (unlikely(fid_is_acct(fid)))
2392                 /* Quota files can't be created from the kernel any more,
2393                  * 'tune2fs -O quota' will take care of creating them */
2394                 RETURN(-EPERM);
2395
2396         osd_trans_exec_op(env, th, OSD_OT_CREATE);
2397         osd_trans_declare_rb(env, th, OSD_OT_REF_ADD);
2398
2399         result = __osd_object_create(info, obj, attr, hint, dof, th);
2400         if (result == 0)
2401                 result = __osd_oi_insert(env, obj, fid, th);
2402
2403         LASSERT(ergo(result == 0,
2404                      dt_object_exists(dt) && !dt_object_remote(dt)));
2405
2406         LASSERT(osd_invariant(obj));
2407         RETURN(result);
2408 }
2409
2410 /**
2411  * Called to destroy on-disk representation of the object
2412  *
2413  * Concurrency: must be locked
2414  */
2415 static int osd_declare_object_destroy(const struct lu_env *env,
2416                                       struct dt_object *dt,
2417                                       struct thandle *th)
2418 {
2419         struct osd_object  *obj = osd_dt_obj(dt);
2420         struct inode       *inode = obj->oo_inode;
2421         struct osd_thandle *oh;
2422         int                 rc;
2423         ENTRY;
2424
2425         oh = container_of0(th, struct osd_thandle, ot_super);
2426         LASSERT(oh->ot_handle == NULL);
2427         LASSERT(inode);
2428
2429         osd_trans_declare_op(env, oh, OSD_OT_DESTROY,
2430                              osd_dto_credits_noquota[DTO_OBJECT_DELETE]);
2431         /* Recycle idle OI leaf may cause additional three OI blocks
2432          * to be changed. */
2433         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
2434                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
2435         /* one less inode */
2436         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, -1, oh,
2437                                    false, true, NULL, false);
2438         if (rc)
2439                 RETURN(rc);
2440         /* data to be truncated */
2441         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0, oh,
2442                                    true, true, NULL, false);
2443         RETURN(rc);
2444 }
2445
2446 static int osd_object_destroy(const struct lu_env *env,
2447                               struct dt_object *dt,
2448                               struct thandle *th)
2449 {
2450         const struct lu_fid    *fid = lu_object_fid(&dt->do_lu);
2451         struct osd_object      *obj = osd_dt_obj(dt);
2452         struct inode           *inode = obj->oo_inode;
2453         struct osd_device      *osd = osd_obj2dev(obj);
2454         struct osd_thandle     *oh;
2455         int                     result;
2456         ENTRY;
2457
2458         oh = container_of0(th, struct osd_thandle, ot_super);
2459         LASSERT(oh->ot_handle);
2460         LASSERT(inode);
2461         LASSERT(!lu_object_is_dying(dt->do_lu.lo_header));
2462
2463         if (unlikely(fid_is_acct(fid)))
2464                 RETURN(-EPERM);
2465
2466         if (S_ISDIR(inode->i_mode)) {
2467                 LASSERT(osd_inode_unlinked(inode) || inode->i_nlink == 1 ||
2468                         inode->i_nlink == 2);
2469                 /* it will check/delete the inode from remote parent,
2470                  * how to optimize it? unlink performance impaction XXX */
2471                 result = osd_delete_from_remote_parent(env, osd, obj, oh);
2472                 if (result != 0 && result != -ENOENT) {
2473                         CERROR("%s: delete inode "DFID": rc = %d\n",
2474                                osd_name(osd), PFID(fid), result);
2475                 }
2476                 spin_lock(&obj->oo_guard);
2477                 clear_nlink(inode);
2478                 spin_unlock(&obj->oo_guard);
2479                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2480         }
2481
2482         osd_trans_exec_op(env, th, OSD_OT_DESTROY);
2483
2484         result = osd_oi_delete(osd_oti_get(env), osd, fid, oh->ot_handle,
2485                                OI_CHECK_FLD);
2486
2487         /* XXX: add to ext3 orphan list */
2488         /* rc = ext3_orphan_add(handle_t *handle, struct inode *inode) */
2489
2490         /* not needed in the cache anymore */
2491         set_bit(LU_OBJECT_HEARD_BANSHEE, &dt->do_lu.lo_header->loh_flags);
2492
2493         RETURN(0);
2494 }
2495
2496 /**
2497  * Put the fid into lustre_mdt_attrs, and then place the structure
2498  * inode's ea. This fid should not be altered during the life time
2499  * of the inode.
2500  *
2501  * \retval +ve, on success
2502  * \retval -ve, on error
2503  *
2504  * FIXME: It is good to have/use ldiskfs_xattr_set_handle() here
2505  */
2506 int osd_ea_fid_set(struct osd_thread_info *info, struct inode *inode,
2507                    const struct lu_fid *fid, __u32 compat, __u32 incompat)
2508 {
2509         struct lustre_mdt_attrs *lma = &info->oti_mdt_attrs;
2510         int                      rc;
2511         ENTRY;
2512
2513         if (OBD_FAIL_CHECK(OBD_FAIL_FID_INLMA))
2514                 RETURN(0);
2515
2516         lustre_lma_init(lma, fid, compat, incompat);
2517         lustre_lma_swab(lma);
2518
2519         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma, sizeof(*lma),
2520                              XATTR_CREATE);
2521         /* LMA may already exist, but we need to check that all the
2522          * desired compat/incompat flags have been added. */
2523         if (unlikely(rc == -EEXIST)) {
2524                 if (compat == 0 && incompat == 0)
2525                         RETURN(0);
2526
2527                 rc = __osd_xattr_get(inode, &info->oti_obj_dentry,
2528                                      XATTR_NAME_LMA, info->oti_mdt_attrs_old,
2529                                      LMA_OLD_SIZE);
2530                 if (rc <= 0)
2531                         RETURN(-EINVAL);
2532
2533                 lustre_lma_swab(lma);
2534                 if (!(~lma->lma_compat & compat) &&
2535                     !(~lma->lma_incompat & incompat))
2536                         RETURN(0);
2537
2538                 lma->lma_compat |= compat;
2539                 lma->lma_incompat |= incompat;
2540                 lustre_lma_swab(lma);
2541                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
2542                                      sizeof(*lma), XATTR_REPLACE);
2543         }
2544
2545         RETURN(rc);
2546 }
2547
2548 /**
2549  * ldiskfs supports fid in dirent, it is passed in dentry->d_fsdata.
2550  * lustre 1.8 also uses d_fsdata for passing other info to ldiskfs.
2551  * To have compatilibility with 1.8 ldiskfs driver we need to have
2552  * magic number at start of fid data.
2553  * \ldiskfs_dentry_param is used only to pass fid from osd to ldiskfs.
2554  * its inmemory API.
2555  */
2556 void osd_get_ldiskfs_dirent_param(struct ldiskfs_dentry_param *param,
2557                                   const struct dt_rec *fid)
2558 {
2559         if (!fid_is_namespace_visible((const struct lu_fid *)fid) ||
2560             OBD_FAIL_CHECK(OBD_FAIL_FID_IGIF)) {
2561                 param->edp_magic = 0;
2562                 return;
2563         }
2564
2565         param->edp_magic = LDISKFS_LUFID_MAGIC;
2566         param->edp_len =  sizeof(struct lu_fid) + 1;
2567         fid_cpu_to_be((struct lu_fid *)param->edp_data, (struct lu_fid *)fid);
2568 }
2569
2570 /**
2571  * Try to read the fid from inode ea into dt_rec.
2572  *
2573  * \param fid object fid.
2574  *
2575  * \retval 0 on success
2576  */
2577 static int osd_ea_fid_get(const struct lu_env *env, struct osd_object *obj,
2578                           __u32 ino, struct lu_fid *fid,
2579                           struct osd_inode_id *id)
2580 {
2581         struct osd_thread_info *info  = osd_oti_get(env);
2582         struct inode           *inode;
2583         ENTRY;
2584
2585         osd_id_gen(id, ino, OSD_OII_NOGEN);
2586         inode = osd_iget_fid(info, osd_obj2dev(obj), id, fid);
2587         if (IS_ERR(inode))
2588                 RETURN(PTR_ERR(inode));
2589
2590         iput(inode);
2591         RETURN(0);
2592 }
2593
2594 static int osd_add_dot_dotdot_internal(struct osd_thread_info *info,
2595                                         struct inode *dir,
2596                                         struct inode  *parent_dir,
2597                                         const struct dt_rec *dot_fid,
2598                                         const struct dt_rec *dot_dot_fid,
2599                                         struct osd_thandle *oth)
2600 {
2601         struct ldiskfs_dentry_param *dot_ldp;
2602         struct ldiskfs_dentry_param *dot_dot_ldp;
2603
2604         dot_dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp2;
2605         osd_get_ldiskfs_dirent_param(dot_dot_ldp, dot_dot_fid);
2606
2607         dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
2608         dot_ldp->edp_magic = 0;
2609         return ldiskfs_add_dot_dotdot(oth->ot_handle, parent_dir,
2610                                         dir, dot_ldp, dot_dot_ldp);
2611 }
2612
2613 /**
2614  * Create an local agent inode for remote entry
2615  */
2616 static struct inode *osd_create_local_agent_inode(const struct lu_env *env,
2617                                                   struct osd_device *osd,
2618                                                   struct osd_object *pobj,
2619                                                   const struct lu_fid *fid,
2620                                                   struct thandle *th)
2621 {
2622         struct osd_thread_info  *info = osd_oti_get(env);
2623         struct inode            *local;
2624         struct osd_thandle      *oh;
2625         int                     rc;
2626         ENTRY;
2627
2628         LASSERT(th);
2629         oh = container_of(th, struct osd_thandle, ot_super);
2630         LASSERT(oh->ot_handle->h_transaction != NULL);
2631
2632         /* FIXME: Insert index api needs to know the mode of
2633          * the remote object. Just use S_IFDIR for now */
2634         local = ldiskfs_create_inode(oh->ot_handle, pobj->oo_inode, S_IFDIR);
2635         if (IS_ERR(local)) {
2636                 CERROR("%s: create local error %d\n", osd_name(osd),
2637                        (int)PTR_ERR(local));
2638                 RETURN(local);
2639         }
2640
2641         /* Set special LMA flag for local agent inode */
2642         rc = osd_ea_fid_set(info, local, fid, 0, LMAI_AGENT);
2643         if (rc != 0) {
2644                 CERROR("%s: set LMA for "DFID" remote inode failed: rc = %d\n",
2645                        osd_name(osd), PFID(fid), rc);
2646                 RETURN(ERR_PTR(rc));
2647         }
2648
2649         rc = osd_add_dot_dotdot_internal(info, local, pobj->oo_inode,
2650                 (const struct dt_rec *)lu_object_fid(&pobj->oo_dt.do_lu),
2651                 (const struct dt_rec *)fid, oh);
2652         if (rc != 0) {
2653                 CERROR("%s: "DFID" add dot dotdot error: rc = %d\n",
2654                         osd_name(osd), PFID(fid), rc);
2655                 RETURN(ERR_PTR(rc));
2656         }
2657
2658         RETURN(local);
2659 }
2660
2661 /**
2662  * Delete local agent inode for remote entry
2663  */
2664 static int osd_delete_local_agent_inode(const struct lu_env *env,
2665                                         struct osd_device *osd,
2666                                         const struct lu_fid *fid,
2667                                         __u32 ino, struct osd_thandle *oh)
2668 {
2669         struct osd_thread_info  *oti = osd_oti_get(env);
2670         struct osd_inode_id     *id = &oti->oti_id;
2671         struct inode            *inode;
2672         ENTRY;
2673
2674         id->oii_ino = le32_to_cpu(ino);
2675         id->oii_gen = OSD_OII_NOGEN;
2676         inode = osd_iget(oti, osd, id);
2677         if (IS_ERR(inode)) {
2678                 CERROR("%s: iget error "DFID" id %u:%u\n", osd_name(osd),
2679                        PFID(fid), id->oii_ino, id->oii_gen);
2680                 RETURN(PTR_ERR(inode));
2681         }
2682
2683         clear_nlink(inode);
2684         mark_inode_dirty(inode);
2685         CDEBUG(D_INODE, "%s: delete remote inode "DFID" %lu\n",
2686                 osd_name(osd), PFID(fid), inode->i_ino);
2687         iput(inode);
2688         RETURN(0);
2689 }
2690
2691 /**
2692  * OSD layer object create function for interoperability mode (b11826).
2693  * This is mostly similar to osd_object_create(). Only difference being, fid is
2694  * inserted into inode ea here.
2695  *
2696  * \retval   0, on success
2697  * \retval -ve, on error
2698  */
2699 static int osd_object_ea_create(const struct lu_env *env, struct dt_object *dt,
2700                                 struct lu_attr *attr,
2701                                 struct dt_allocation_hint *hint,
2702                                 struct dt_object_format *dof,
2703                                 struct thandle *th)
2704 {
2705         const struct lu_fid    *fid    = lu_object_fid(&dt->do_lu);
2706         struct osd_object      *obj    = osd_dt_obj(dt);
2707         struct osd_thread_info *info   = osd_oti_get(env);
2708         int                     result;
2709
2710         ENTRY;
2711
2712         LASSERT(osd_invariant(obj));
2713         LASSERT(!dt_object_exists(dt) && !dt_object_remote(dt));
2714         LASSERT(osd_write_locked(env, obj));
2715         LASSERT(th != NULL);
2716
2717         if (unlikely(fid_is_acct(fid)))
2718                 /* Quota files can't be created from the kernel any more,
2719                  * 'tune2fs -O quota' will take care of creating them */
2720                 RETURN(-EPERM);
2721
2722         osd_trans_exec_op(env, th, OSD_OT_CREATE);
2723         osd_trans_declare_rb(env, th, OSD_OT_REF_ADD);
2724
2725         result = __osd_object_create(info, obj, attr, hint, dof, th);
2726         if (result == 0)
2727                 result = osd_ea_fid_set(info, obj->oo_inode, fid,
2728                                 fid_is_on_ost(info, osd_obj2dev(obj),
2729                                               fid, OI_CHECK_FLD) ?
2730                                 LMAC_FID_ON_OST : 0, 0);
2731
2732         if (result == 0)
2733                 result = __osd_oi_insert(env, obj, fid, th);
2734
2735         LASSERT(ergo(result == 0,
2736                      dt_object_exists(dt) && !dt_object_remote(dt)));
2737         LINVRNT(osd_invariant(obj));
2738         RETURN(result);
2739 }
2740
2741 static int osd_declare_object_ref_add(const struct lu_env *env,
2742                                       struct dt_object *dt,
2743                                       struct thandle *handle)
2744 {
2745         struct osd_thandle       *oh;
2746
2747         /* it's possible that object doesn't exist yet */
2748         LASSERT(handle != NULL);
2749
2750         oh = container_of0(handle, struct osd_thandle, ot_super);
2751         LASSERT(oh->ot_handle == NULL);
2752
2753         osd_trans_declare_op(env, oh, OSD_OT_REF_ADD,
2754                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2755
2756         return 0;
2757 }
2758
2759 /*
2760  * Concurrency: @dt is write locked.
2761  */
2762 static int osd_object_ref_add(const struct lu_env *env,
2763                               struct dt_object *dt, struct thandle *th)
2764 {
2765         struct osd_object  *obj = osd_dt_obj(dt);
2766         struct inode       *inode = obj->oo_inode;
2767         struct osd_thandle *oh;
2768         int                 rc = 0;
2769
2770         LINVRNT(osd_invariant(obj));
2771         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2772         LASSERT(osd_write_locked(env, obj));
2773         LASSERT(th != NULL);
2774
2775         oh = container_of0(th, struct osd_thandle, ot_super);
2776         LASSERT(oh->ot_handle != NULL);
2777
2778         osd_trans_exec_op(env, th, OSD_OT_REF_ADD);
2779
2780         /*
2781          * The DIR_NLINK feature allows directories to exceed LDISKFS_LINK_MAX
2782          * (65000) subdirectories by storing "1" in i_nlink if the link count
2783          * would otherwise overflow. Directory tranversal tools understand
2784          * that (st_nlink == 1) indicates that the filesystem dose not track
2785          * hard links count on the directory, and will not abort subdirectory
2786          * scanning early once (st_nlink - 2) subdirs have been found.
2787          *
2788          * This also has to properly handle the case of inodes with nlink == 0
2789          * in case they are being linked into the PENDING directory
2790          */
2791         spin_lock(&obj->oo_guard);
2792         ldiskfs_inc_count(oh->ot_handle, inode);
2793         LASSERT(inode->i_nlink <= LDISKFS_LINK_MAX);
2794         spin_unlock(&obj->oo_guard);
2795
2796         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2797         LINVRNT(osd_invariant(obj));
2798
2799         return rc;
2800 }
2801
2802 static int osd_declare_object_ref_del(const struct lu_env *env,
2803                                       struct dt_object *dt,
2804                                       struct thandle *handle)
2805 {
2806         struct osd_thandle *oh;
2807
2808         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2809         LASSERT(handle != NULL);
2810
2811         oh = container_of0(handle, struct osd_thandle, ot_super);
2812         LASSERT(oh->ot_handle == NULL);
2813
2814         osd_trans_declare_op(env, oh, OSD_OT_REF_DEL,
2815                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2816
2817         return 0;
2818 }
2819
2820 /*
2821  * Concurrency: @dt is write locked.
2822  */
2823 static int osd_object_ref_del(const struct lu_env *env, struct dt_object *dt,
2824                               struct thandle *th)
2825 {
2826         struct osd_object       *obj = osd_dt_obj(dt);
2827         struct inode            *inode = obj->oo_inode;
2828         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
2829         struct osd_thandle      *oh;
2830
2831         LINVRNT(osd_invariant(obj));
2832         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2833         LASSERT(osd_write_locked(env, obj));
2834         LASSERT(th != NULL);
2835
2836         oh = container_of0(th, struct osd_thandle, ot_super);
2837         LASSERT(oh->ot_handle != NULL);
2838
2839         osd_trans_exec_op(env, th, OSD_OT_REF_DEL);
2840
2841         spin_lock(&obj->oo_guard);
2842         /* That can be result of upgrade from old Lustre version and
2843          * applied only to local files.  Just skip this ref_del call.
2844          * ext4_unlink() only treats this as a warning, don't LASSERT here.*/
2845         if (inode->i_nlink == 0) {
2846                 CDEBUG_LIMIT(fid_is_norm(lu_object_fid(&dt->do_lu)) ?
2847                              D_ERROR : D_INODE, "%s: nlink == 0 on "DFID
2848                              ", maybe an upgraded file? (LU-3915)\n",
2849                              osd_name(osd), PFID(lu_object_fid(&dt->do_lu)));
2850                 spin_unlock(&obj->oo_guard);
2851                 return 0;
2852         }
2853
2854         ldiskfs_dec_count(oh->ot_handle, inode);
2855         spin_unlock(&obj->oo_guard);
2856
2857         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2858         LINVRNT(osd_invariant(obj));
2859
2860         return 0;
2861 }
2862
2863 /*
2864  * Get the 64-bit version for an inode.
2865  */
2866 static int osd_object_version_get(const struct lu_env *env,
2867                                   struct dt_object *dt, dt_obj_version_t *ver)
2868 {
2869         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2870
2871         CDEBUG(D_INODE, "Get version "LPX64" for inode %lu\n",
2872                LDISKFS_I(inode)->i_fs_version, inode->i_ino);
2873         *ver = LDISKFS_I(inode)->i_fs_version;
2874         return 0;
2875 }
2876
2877 /*
2878  * Concurrency: @dt is read locked.
2879  */
2880 static int osd_xattr_get(const struct lu_env *env, struct dt_object *dt,
2881                          struct lu_buf *buf, const char *name,
2882                          struct lustre_capa *capa)
2883 {
2884         struct osd_object      *obj    = osd_dt_obj(dt);
2885         struct inode           *inode  = obj->oo_inode;
2886         struct osd_thread_info *info   = osd_oti_get(env);
2887         struct dentry          *dentry = &info->oti_obj_dentry;
2888
2889         /* version get is not real XATTR but uses xattr API */
2890         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2891                 /* for version we are just using xattr API but change inode
2892                  * field instead */
2893                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
2894                 osd_object_version_get(env, dt, buf->lb_buf);
2895                 return sizeof(dt_obj_version_t);
2896         }
2897
2898         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2899         LASSERT(inode->i_op != NULL && inode->i_op->getxattr != NULL);
2900
2901         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
2902                 return -EACCES;
2903
2904         return __osd_xattr_get(inode, dentry, name, buf->lb_buf, buf->lb_len);
2905 }
2906
2907
2908 static int osd_declare_xattr_set(const struct lu_env *env,
2909                                  struct dt_object *dt,
2910                                  const struct lu_buf *buf, const char *name,
2911                                  int fl, struct thandle *handle)
2912 {
2913         struct osd_thandle *oh;
2914
2915         LASSERT(handle != NULL);
2916
2917         oh = container_of0(handle, struct osd_thandle, ot_super);
2918         LASSERT(oh->ot_handle == NULL);
2919
2920         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2921                              strcmp(name, XATTR_NAME_VERSION) == 0 ?
2922                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE] :
2923                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2924
2925         return 0;
2926 }
2927
2928 /*
2929  * Set the 64-bit version for object
2930  */
2931 static void osd_object_version_set(const struct lu_env *env,
2932                                    struct dt_object *dt,
2933                                    dt_obj_version_t *new_version)
2934 {
2935         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2936
2937         CDEBUG(D_INODE, "Set version "LPX64" (old "LPX64") for inode %lu\n",
2938                *new_version, LDISKFS_I(inode)->i_fs_version, inode->i_ino);
2939
2940         LDISKFS_I(inode)->i_fs_version = *new_version;
2941         /** Version is set after all inode operations are finished,
2942          *  so we should mark it dirty here */
2943         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2944 }
2945
2946 /*
2947  * Concurrency: @dt is write locked.
2948  */
2949 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
2950                          const struct lu_buf *buf, const char *name, int fl,
2951                          struct thandle *handle, struct lustre_capa *capa)
2952 {
2953         struct osd_object      *obj      = osd_dt_obj(dt);
2954         struct inode           *inode    = obj->oo_inode;
2955         struct osd_thread_info *info     = osd_oti_get(env);
2956         int                     fs_flags = 0;
2957         ENTRY;
2958
2959         LASSERT(handle != NULL);
2960
2961         /* version set is not real XATTR */
2962         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2963                 /* for version we are just using xattr API but change inode
2964                  * field instead */
2965                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
2966                 osd_object_version_set(env, dt, buf->lb_buf);
2967                 return sizeof(dt_obj_version_t);
2968         }
2969
2970         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
2971                 return -EACCES;
2972
2973         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
2974         if (fl & LU_XATTR_REPLACE)
2975                 fs_flags |= XATTR_REPLACE;
2976
2977         if (fl & LU_XATTR_CREATE)
2978                 fs_flags |= XATTR_CREATE;
2979
2980         return __osd_xattr_set(info, inode, name, buf->lb_buf, buf->lb_len,
2981                                fs_flags);
2982 }
2983
2984 /*
2985  * Concurrency: @dt is read locked.
2986  */
2987 static int osd_xattr_list(const struct lu_env *env, struct dt_object *dt,
2988                           struct lu_buf *buf, struct lustre_capa *capa)
2989 {
2990         struct osd_object      *obj    = osd_dt_obj(dt);
2991         struct inode           *inode  = obj->oo_inode;
2992         struct osd_thread_info *info   = osd_oti_get(env);
2993         struct dentry          *dentry = &info->oti_obj_dentry;
2994
2995         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2996         LASSERT(inode->i_op != NULL && inode->i_op->listxattr != NULL);
2997         LASSERT(osd_read_locked(env, obj) || osd_write_locked(env, obj));
2998
2999         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
3000                 return -EACCES;
3001
3002         dentry->d_inode = inode;
3003         dentry->d_sb = inode->i_sb;
3004         return inode->i_op->listxattr(dentry, buf->lb_buf, buf->lb_len);
3005 }
3006
3007 static int osd_declare_xattr_del(const struct lu_env *env,
3008                                  struct dt_object *dt, const char *name,
3009                                  struct thandle *handle)
3010 {
3011         struct osd_thandle *oh;
3012
3013         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3014         LASSERT(handle != NULL);
3015
3016         oh = container_of0(handle, struct osd_thandle, ot_super);
3017         LASSERT(oh->ot_handle == NULL);
3018
3019         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
3020                              osd_dto_credits_noquota[DTO_XATTR_SET]);
3021
3022         return 0;
3023 }
3024
3025 /*
3026  * Concurrency: @dt is write locked.
3027  */
3028 static int osd_xattr_del(const struct lu_env *env, struct dt_object *dt,
3029                          const char *name, struct thandle *handle,
3030                          struct lustre_capa *capa)
3031 {
3032         struct osd_object      *obj    = osd_dt_obj(dt);
3033         struct inode           *inode  = obj->oo_inode;
3034         struct osd_thread_info *info   = osd_oti_get(env);
3035         struct dentry          *dentry = &info->oti_obj_dentry;
3036         int                     rc;
3037
3038         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3039         LASSERT(inode->i_op != NULL && inode->i_op->removexattr != NULL);
3040         LASSERT(handle != NULL);
3041
3042         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
3043                 return -EACCES;
3044
3045         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
3046
3047         ll_vfs_dq_init(inode);
3048         dentry->d_inode = inode;
3049         dentry->d_sb = inode->i_sb;
3050         rc = inode->i_op->removexattr(dentry, name);
3051         return rc;
3052 }
3053
3054 static struct obd_capa *osd_capa_get(const struct lu_env *env,
3055                                      struct dt_object *dt,
3056                                      struct lustre_capa *old, __u64 opc)
3057 {
3058         struct osd_thread_info *info = osd_oti_get(env);
3059         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
3060         struct osd_object *obj = osd_dt_obj(dt);
3061         struct osd_device *osd = osd_obj2dev(obj);
3062         struct lustre_capa_key *key = &info->oti_capa_key;
3063         struct lustre_capa *capa = &info->oti_capa;
3064         struct obd_capa *oc;
3065         struct lu_capainfo *lci;
3066         int rc;
3067         ENTRY;
3068
3069         if (!osd->od_fl_capa)
3070                 RETURN(ERR_PTR(-ENOENT));
3071
3072         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3073         LINVRNT(osd_invariant(obj));
3074
3075         /* renewal sanity check */
3076         if (old && osd_object_auth(env, dt, old, opc))
3077                 RETURN(ERR_PTR(-EACCES));
3078
3079         lci = lu_capainfo_get(env);
3080         if (unlikely(lci == NULL))
3081                 RETURN(ERR_PTR(-ENOENT));
3082
3083         switch (lci->lci_auth) {
3084         case LC_ID_NONE:
3085                 RETURN(NULL);
3086         case LC_ID_PLAIN:
3087                 capa->lc_uid = obj->oo_inode->i_uid;
3088                 capa->lc_gid = obj->oo_inode->i_gid;
3089                 capa->lc_flags = LC_ID_PLAIN;
3090                 break;
3091         case LC_ID_CONVERT: {
3092                 __u32 d[4], s[4];
3093
3094                 s[0] = obj->oo_inode->i_uid;
3095                 cfs_get_random_bytes(&(s[1]), sizeof(__u32));
3096                 s[2] = obj->oo_inode->i_gid;
3097                 cfs_get_random_bytes(&(s[3]), sizeof(__u32));
3098                 rc = capa_encrypt_id(d, s, key->lk_key, CAPA_HMAC_KEY_MAX_LEN);
3099                 if (unlikely(rc))
3100                         RETURN(ERR_PTR(rc));
3101
3102                 capa->lc_uid   = ((__u64)d[1] << 32) | d[0];
3103                 capa->lc_gid   = ((__u64)d[3] << 32) | d[2];
3104                 capa->lc_flags = LC_ID_CONVERT;
3105                 break;
3106         }
3107         default:
3108                 RETURN(ERR_PTR(-EINVAL));
3109         }
3110
3111         capa->lc_fid = *fid;
3112         capa->lc_opc = opc;
3113         capa->lc_flags |= osd->od_capa_alg << 24;
3114         capa->lc_timeout = osd->od_capa_timeout;
3115         capa->lc_expiry = 0;
3116
3117         oc = capa_lookup(osd->od_capa_hash, capa, 1);
3118         if (oc) {
3119                 LASSERT(!capa_is_expired(oc));
3120                 RETURN(oc);
3121         }
3122
3123         spin_lock(&capa_lock);
3124         *key = osd->od_capa_keys[1];
3125         spin_unlock(&capa_lock);
3126
3127         capa->lc_keyid = key->lk_keyid;
3128         capa->lc_expiry = cfs_time_current_sec() + osd->od_capa_timeout;
3129
3130         rc = capa_hmac(capa->lc_hmac, capa, key->lk_key);
3131         if (rc) {
3132                 DEBUG_CAPA(D_ERROR, capa, "HMAC failed: %d for", rc);
3133                 RETURN(ERR_PTR(rc));
3134         }
3135
3136         oc = capa_add(osd->od_capa_hash, capa);
3137         RETURN(oc);
3138 }
3139
3140 static int osd_object_sync(const struct lu_env *env, struct dt_object *dt)
3141 {
3142         struct osd_object       *obj    = osd_dt_obj(dt);
3143         struct inode            *inode  = obj->oo_inode;
3144         struct osd_thread_info  *info   = osd_oti_get(env);
3145         struct dentry           *dentry = &info->oti_obj_dentry;
3146         struct file             *file   = &info->oti_file;
3147         int                     rc;
3148
3149         ENTRY;
3150
3151         dentry->d_inode = inode;
3152         dentry->d_sb = inode->i_sb;
3153         file->f_dentry = dentry;
3154         file->f_mapping = inode->i_mapping;
3155         file->f_op = inode->i_fop;
3156         set_file_inode(file, inode);
3157 #ifndef HAVE_FILE_FSYNC_4ARGS
3158         mutex_lock(&inode->i_mutex);
3159 #endif
3160         rc = do_fsync(file, 0);
3161 #ifndef HAVE_FILE_FSYNC_4ARGS
3162         mutex_unlock(&inode->i_mutex);
3163 #endif
3164         RETURN(rc);
3165 }
3166
3167 static int osd_data_get(const struct lu_env *env, struct dt_object *dt,
3168                         void **data)
3169 {
3170         struct osd_object *obj = osd_dt_obj(dt);
3171         ENTRY;
3172
3173         *data = (void *)obj->oo_inode;
3174         RETURN(0);
3175 }
3176
3177 /*
3178  * Index operations.
3179  */
3180
3181 static int osd_iam_index_probe(const struct lu_env *env, struct osd_object *o,
3182                            const struct dt_index_features *feat)
3183 {
3184         struct iam_descr *descr;
3185
3186         if (osd_object_is_root(o))
3187                 return feat == &dt_directory_features;
3188
3189         LASSERT(o->oo_dir != NULL);
3190
3191         descr = o->oo_dir->od_container.ic_descr;
3192         if (feat == &dt_directory_features) {
3193                 if (descr->id_rec_size == sizeof(struct osd_fid_pack))
3194                         return 1;
3195                 else
3196                         return 0;
3197         } else {
3198                 return
3199                         feat->dif_keysize_min <= descr->id_key_size &&
3200                         descr->id_key_size <= feat->dif_keysize_max &&
3201                         feat->dif_recsize_min <= descr->id_rec_size &&
3202                         descr->id_rec_size <= feat->dif_recsize_max &&
3203                         !(feat->dif_flags & (DT_IND_VARKEY |
3204                                              DT_IND_VARREC | DT_IND_NONUNQ)) &&
3205                         ergo(feat->dif_flags & DT_IND_UPDATE,
3206                              1 /* XXX check that object (and file system) is
3207                                 * writable */);
3208         }
3209 }
3210
3211 static int osd_iam_container_init(const struct lu_env *env,
3212                                   struct osd_object *obj,
3213                                   struct osd_directory *dir)
3214 {
3215         struct iam_container *bag = &dir->od_container;
3216         int result;
3217
3218         result = iam_container_init(bag, &dir->od_descr, obj->oo_inode);
3219         if (result != 0)
3220                 return result;
3221
3222         result = iam_container_setup(bag);
3223         if (result == 0)
3224                 obj->oo_dt.do_index_ops = &osd_index_iam_ops;
3225         else
3226                 iam_container_fini(bag);
3227
3228         return result;
3229 }
3230
3231
3232 /*
3233  * Concurrency: no external locking is necessary.
3234  */
3235 static int osd_index_try(const struct lu_env *env, struct dt_object *dt,
3236                          const struct dt_index_features *feat)
3237 {
3238         int                      result;
3239         int                      skip_iam = 0;
3240         struct osd_object       *obj = osd_dt_obj(dt);
3241
3242         LINVRNT(osd_invariant(obj));
3243
3244         if (osd_object_is_root(obj)) {
3245                 dt->do_index_ops = &osd_index_ea_ops;
3246                 result = 0;
3247         } else if (feat == &dt_directory_features) {
3248                 dt->do_index_ops = &osd_index_ea_ops;
3249                 if (obj->oo_inode != NULL && S_ISDIR(obj->oo_inode->i_mode))
3250                         result = 0;
3251                 else
3252                         result = -ENOTDIR;
3253                 skip_iam = 1;
3254         } else if (unlikely(feat == &dt_otable_features)) {
3255                 dt->do_index_ops = &osd_otable_ops;
3256                 return 0;
3257         } else if (unlikely(feat == &dt_acct_features)) {
3258                 dt->do_index_ops = &osd_acct_index_ops;
3259                 result = 0;
3260                 skip_iam = 1;
3261         } else if (!osd_has_index(obj)) {
3262                 struct osd_directory *dir;
3263
3264                 OBD_ALLOC_PTR(dir);
3265                 if (dir != NULL) {
3266
3267                         spin_lock(&obj->oo_guard);
3268                         if (obj->oo_dir == NULL)
3269                                 obj->oo_dir = dir;
3270                         else
3271                                 /*
3272                                  * Concurrent thread allocated container data.
3273                                  */
3274                                 OBD_FREE_PTR(dir);
3275                         spin_unlock(&obj->oo_guard);
3276                         /*
3277                          * Now, that we have container data, serialize its
3278                          * initialization.
3279                          */
3280                         down_write(&obj->oo_ext_idx_sem);
3281                         /*
3282                          * recheck under lock.
3283                          */
3284                         if (!osd_has_index(obj))
3285                                 result = osd_iam_container_init(env, obj, dir);
3286                         else
3287                                 result = 0;
3288                         up_write(&obj->oo_ext_idx_sem);
3289                 } else {
3290                         result = -ENOMEM;
3291                 }
3292         } else {
3293                 result = 0;
3294         }
3295
3296         if (result == 0 && skip_iam == 0) {
3297                 if (!osd_iam_index_probe(env, obj, feat))
3298                         result = -ENOTDIR;
3299         }
3300         LINVRNT(osd_invariant(obj));
3301
3302         if (result == 0 && is_quota_glb_feat(feat) &&
3303             fid_seq(lu_object_fid(&dt->do_lu)) == FID_SEQ_QUOTA_GLB)
3304                 result = osd_quota_migration(env, dt, feat);
3305
3306         return result;
3307 }
3308
3309 static int osd_otable_it_attr_get(const struct lu_env *env,
3310                                  struct dt_object *dt,
3311                                  struct lu_attr *attr,
3312                                  struct lustre_capa *capa)
3313 {
3314         attr->la_valid = 0;
3315         return 0;
3316 }
3317
3318 static const struct dt_object_operations osd_obj_ops = {
3319         .do_read_lock         = osd_object_read_lock,
3320         .do_write_lock        = osd_object_write_lock,
3321         .do_read_unlock       = osd_object_read_unlock,
3322         .do_write_unlock      = osd_object_write_unlock,
3323         .do_write_locked      = osd_object_write_locked,
3324         .do_attr_get          = osd_attr_get,
3325         .do_declare_attr_set  = osd_declare_attr_set,
3326         .do_attr_set          = osd_attr_set,
3327         .do_ah_init           = osd_ah_init,
3328         .do_declare_create    = osd_declare_object_create,
3329         .do_create            = osd_object_create,
3330         .do_declare_destroy   = osd_declare_object_destroy,
3331         .do_destroy           = osd_object_destroy,
3332         .do_index_try         = osd_index_try,
3333         .do_declare_ref_add   = osd_declare_object_ref_add,
3334         .do_ref_add           = osd_object_ref_add,
3335         .do_declare_ref_del   = osd_declare_object_ref_del,
3336         .do_ref_del           = osd_object_ref_del,
3337         .do_xattr_get         = osd_xattr_get,
3338         .do_declare_xattr_set = osd_declare_xattr_set,
3339         .do_xattr_set         = osd_xattr_set,
3340         .do_declare_xattr_del = osd_declare_xattr_del,
3341         .do_xattr_del         = osd_xattr_del,
3342         .do_xattr_list        = osd_xattr_list,
3343         .do_capa_get          = osd_capa_get,
3344         .do_object_sync       = osd_object_sync,
3345         .do_data_get          = osd_data_get,
3346 };
3347
3348 /**
3349  * dt_object_operations for interoperability mode
3350  * (i.e. to run 2.0 mds on 1.8 disk) (b11826)
3351  */
3352 static const struct dt_object_operations osd_obj_ea_ops = {
3353         .do_read_lock         = osd_object_read_lock,
3354         .do_write_lock        = osd_object_write_lock,
3355         .do_read_unlock       = osd_object_read_unlock,
3356         .do_write_unlock      = osd_object_write_unlock,
3357         .do_write_locked      = osd_object_write_locked,
3358         .do_attr_get          = osd_attr_get,
3359         .do_declare_attr_set  = osd_declare_attr_set,
3360         .do_attr_set          = osd_attr_set,
3361         .do_ah_init           = osd_ah_init,
3362         .do_declare_create    = osd_declare_object_create,
3363         .do_create            = osd_object_ea_create,
3364         .do_declare_destroy   = osd_declare_object_destroy,
3365         .do_destroy           = osd_object_destroy,
3366         .do_index_try         = osd_index_try,
3367         .do_declare_ref_add   = osd_declare_object_ref_add,
3368         .do_ref_add           = osd_object_ref_add,
3369         .do_declare_ref_del   = osd_declare_object_ref_del,
3370         .do_ref_del           = osd_object_ref_del,
3371         .do_xattr_get         = osd_xattr_get,
3372         .do_declare_xattr_set = osd_declare_xattr_set,
3373         .do_xattr_set         = osd_xattr_set,
3374         .do_declare_xattr_del = osd_declare_xattr_del,
3375         .do_xattr_del         = osd_xattr_del,
3376         .do_xattr_list        = osd_xattr_list,
3377         .do_capa_get          = osd_capa_get,
3378         .do_object_sync       = osd_object_sync,
3379         .do_data_get          = osd_data_get,
3380 };
3381
3382 static const struct dt_object_operations osd_obj_otable_it_ops = {
3383         .do_attr_get    = osd_otable_it_attr_get,
3384         .do_index_try   = osd_index_try,
3385 };
3386
3387 static int osd_index_declare_iam_delete(const struct lu_env *env,
3388                                         struct dt_object *dt,
3389                                         const struct dt_key *key,
3390                                         struct thandle *handle)
3391 {
3392         struct osd_thandle    *oh;
3393
3394         oh = container_of0(handle, struct osd_thandle, ot_super);
3395         LASSERT(oh->ot_handle == NULL);
3396
3397         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3398                              osd_dto_credits_noquota[DTO_INDEX_DELETE]);
3399
3400         return 0;
3401 }
3402
3403 /**
3404  *      delete a (key, value) pair from index \a dt specified by \a key
3405  *
3406  *      \param  dt      osd index object
3407  *      \param  key     key for index
3408  *      \param  rec     record reference
3409  *      \param  handle  transaction handler
3410  *
3411  *      \retval  0  success
3412  *      \retval -ve   failure
3413  */
3414
3415 static int osd_index_iam_delete(const struct lu_env *env, struct dt_object *dt,
3416                                 const struct dt_key *key,
3417                                 struct thandle *handle,
3418                                 struct lustre_capa *capa)
3419 {
3420         struct osd_thread_info *oti = osd_oti_get(env);
3421         struct osd_object      *obj = osd_dt_obj(dt);
3422         struct osd_thandle     *oh;
3423         struct iam_path_descr  *ipd;
3424         struct iam_container   *bag = &obj->oo_dir->od_container;
3425         int                     rc;
3426
3427         ENTRY;
3428
3429         LINVRNT(osd_invariant(obj));
3430         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3431         LASSERT(bag->ic_object == obj->oo_inode);
3432         LASSERT(handle != NULL);
3433
3434         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
3435                 RETURN(-EACCES);
3436
3437         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3438
3439         ipd = osd_idx_ipd_get(env, bag);
3440         if (unlikely(ipd == NULL))
3441                 RETURN(-ENOMEM);
3442
3443         oh = container_of0(handle, struct osd_thandle, ot_super);
3444         LASSERT(oh->ot_handle != NULL);
3445         LASSERT(oh->ot_handle->h_transaction != NULL);
3446
3447         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3448                 /* swab quota uid/gid provided by caller */
3449                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3450                 key = (const struct dt_key *)&oti->oti_quota_id;
3451         }
3452
3453         rc = iam_delete(oh->ot_handle, bag, (const struct iam_key *)key, ipd);
3454         osd_ipd_put(env, bag, ipd);
3455         LINVRNT(osd_invariant(obj));
3456         RETURN(rc);
3457 }
3458
3459 static int osd_index_declare_ea_delete(const struct lu_env *env,
3460                                        struct dt_object *dt,
3461                                        const struct dt_key *key,
3462                                        struct thandle *handle)
3463 {
3464         struct osd_thandle *oh;
3465         struct inode       *inode;
3466         int                 rc;
3467         ENTRY;
3468
3469         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3470         LASSERT(handle != NULL);
3471
3472         oh = container_of0(handle, struct osd_thandle, ot_super);
3473         LASSERT(oh->ot_handle == NULL);
3474
3475         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3476                              osd_dto_credits_noquota[DTO_INDEX_DELETE]);
3477
3478         inode = osd_dt_obj(dt)->oo_inode;
3479         LASSERT(inode);
3480
3481         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0, oh,
3482                                    true, true, NULL, false);
3483         RETURN(rc);
3484 }
3485
3486 static inline int osd_get_fid_from_dentry(struct ldiskfs_dir_entry_2 *de,
3487                                           struct dt_rec *fid)
3488 {
3489         struct osd_fid_pack *rec;
3490         int                  rc = -ENODATA;
3491
3492         if (de->file_type & LDISKFS_DIRENT_LUFID) {
3493                 rec = (struct osd_fid_pack *) (de->name + de->name_len + 1);
3494                 rc = osd_fid_unpack((struct lu_fid *)fid, rec);
3495         }
3496         return rc;
3497 }
3498
3499 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
3500                           struct lu_fid *fid)
3501 {
3502         ENTRY;
3503
3504         /* FID seqs not in FLDB, must be local seq */
3505         if (unlikely(!fid_seq_in_fldb(fid_seq(fid))))
3506                 RETURN(0);
3507
3508         if (osd_seq_exists(env, osd, fid_seq(fid)))
3509                 RETURN(0);
3510
3511         RETURN(1);
3512 }
3513
3514 /**
3515  * Index delete function for interoperability mode (b11826).
3516  * It will remove the directory entry added by osd_index_ea_insert().
3517  * This entry is needed to maintain name->fid mapping.
3518  *
3519  * \param key,  key i.e. file entry to be deleted
3520  *
3521  * \retval   0, on success
3522  * \retval -ve, on error
3523  */
3524 static int osd_index_ea_delete(const struct lu_env *env, struct dt_object *dt,
3525                                const struct dt_key *key,
3526                                struct thandle *handle,
3527                                struct lustre_capa *capa)
3528 {
3529         struct osd_object          *obj    = osd_dt_obj(dt);
3530         struct inode               *dir    = obj->oo_inode;
3531         struct dentry              *dentry;
3532         struct osd_thandle         *oh;
3533         struct ldiskfs_dir_entry_2 *de = NULL;
3534         struct buffer_head         *bh;
3535         struct htree_lock          *hlock = NULL;
3536         struct lu_fid              *fid = &osd_oti_get(env)->oti_fid;
3537         struct osd_device          *osd = osd_dev(dt->do_lu.lo_dev);
3538         int                        rc;
3539         ENTRY;
3540
3541         LINVRNT(osd_invariant(obj));
3542         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3543         LASSERT(handle != NULL);
3544
3545         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3546
3547         oh = container_of(handle, struct osd_thandle, ot_super);
3548         LASSERT(oh->ot_handle != NULL);
3549         LASSERT(oh->ot_handle->h_transaction != NULL);
3550
3551         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
3552                 RETURN(-EACCES);
3553
3554         ll_vfs_dq_init(dir);
3555         dentry = osd_child_dentry_get(env, obj,
3556                                       (char *)key, strlen((char *)key));
3557
3558         if (obj->oo_hl_head != NULL) {
3559                 hlock = osd_oti_get(env)->oti_hlock;
3560                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
3561                                    dir, LDISKFS_HLOCK_DEL);
3562         } else {
3563                 down_write(&obj->oo_ext_idx_sem);
3564         }
3565
3566         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
3567         if (bh) {
3568                 __u32 ino = 0;
3569
3570                 /* If this is not the ".." entry, it might be a remote DNE
3571                  * entry and  we need to check if the FID is for a remote
3572                  * MDT.  If the FID is  not in the directory entry (e.g.
3573                  * upgraded 1.8 filesystem without dirdata enabled) then
3574                  * we need to get the FID from the LMA. For a remote directory
3575                  * there HAS to be an LMA, it cannot be an IGIF inode in this
3576                  * case.
3577                  *
3578                  * Delete the entry before the agent inode in order to
3579                  * simplify error handling.  At worst an error after deleting
3580                  * the entry first might leak the agent inode afterward. The
3581                  * reverse would need filesystem abort in case of error deleting
3582                  * the entry after the agent had been removed, or leave a
3583                  * dangling entry pointing at a random inode. */
3584                 if (strcmp((char *)key, dotdot) != 0) {
3585                         LASSERT(de != NULL);
3586                         rc = osd_get_fid_from_dentry(de, (struct dt_rec *)fid);
3587                         /* If Fid is not in dentry, try to get it from LMA */
3588                         if (rc == -ENODATA) {
3589                                 struct osd_inode_id *id;
3590                                 struct inode *inode;
3591
3592                                 /* Before trying to get fid from the inode,
3593                                  * check whether the inode is valid.
3594                                  *
3595                                  * If the inode has been deleted, do not go
3596                                  * ahead to do osd_ea_fid_get, which will set
3597                                  * the inode to bad inode, which might cause
3598                                  * the inode to be deleted uncorrectly */
3599                                 inode = ldiskfs_iget(osd_sb(osd),
3600                                                      le32_to_cpu(de->inode));
3601                                 if (IS_ERR(inode)) {
3602                                         CDEBUG(D_INODE, "%s: "DFID"get inode"
3603                                                "error.\n", osd_name(osd),
3604                                                PFID(fid));
3605                                         rc = PTR_ERR(inode);
3606                                 } else {
3607                                         if (likely(inode->i_nlink != 0)) {
3608                                                 id = &osd_oti_get(env)->oti_id;
3609                                                 rc = osd_ea_fid_get(env, obj,
3610                                                         le32_to_cpu(de->inode),
3611                                                                     fid, id);
3612                                         } else {
3613                                                 CDEBUG(D_INFO, "%s: %u "DFID
3614                                                        "deleted.\n",
3615                                                        osd_name(osd),
3616                                                        le32_to_cpu(de->inode),
3617                                                        PFID(fid));
3618                                                 rc = -ESTALE;
3619                                         }
3620                                         iput(inode);
3621                                 }
3622                         }
3623                         if (rc == 0 &&
3624                             unlikely(osd_remote_fid(env, osd, fid)))
3625                                 /* Need to delete agent inode */
3626                                 ino = le32_to_cpu(de->inode);
3627                 }
3628                 rc = ldiskfs_delete_entry(oh->ot_handle, dir, de, bh);
3629                 brelse(bh);
3630                 if (rc == 0 && unlikely(ino != 0)) {
3631                         rc = osd_delete_local_agent_inode(env, osd, fid, ino,
3632                                                           oh);
3633                         if (rc != 0)
3634                                 CERROR("%s: del local inode "DFID": rc = %d\n",
3635                                        osd_name(osd), PFID(fid), rc);
3636                 }
3637         } else {
3638                 rc = -ENOENT;
3639         }
3640         if (hlock != NULL)
3641                 ldiskfs_htree_unlock(hlock);
3642         else
3643                 up_write(&obj->oo_ext_idx_sem);
3644
3645         if (rc != 0)
3646                 GOTO(out, rc);
3647
3648         /* For inode on the remote MDT, .. will point to
3649          * /Agent directory, Check whether it needs to delete
3650          * from agent directory */
3651         if (unlikely(strcmp((char *)key, dotdot) == 0)) {
3652                 rc = osd_delete_from_remote_parent(env, osd_obj2dev(obj), obj,
3653                                                    oh);
3654                 if (rc != 0 && rc != -ENOENT) {
3655                         CERROR("%s: delete agent inode "DFID": rc = %d\n",
3656                                osd_name(osd), PFID(fid), rc);
3657                 }
3658
3659                 if (rc == -ENOENT)
3660                         rc = 0;
3661
3662                 GOTO(out, rc);
3663         }
3664 out:
3665
3666         LASSERT(osd_invariant(obj));
3667         RETURN(rc);
3668 }
3669
3670 /**
3671  *      Lookup index for \a key and copy record to \a rec.
3672  *
3673  *      \param  dt      osd index object
3674  *      \param  key     key for index
3675  *      \param  rec     record reference
3676  *
3677  *      \retval  +ve  success : exact mach
3678  *      \retval  0    return record with key not greater than \a key
3679  *      \retval -ve   failure
3680  */
3681 static int osd_index_iam_lookup(const struct lu_env *env, struct dt_object *dt,
3682                                 struct dt_rec *rec, const struct dt_key *key,
3683                                 struct lustre_capa *capa)
3684 {
3685         struct osd_object      *obj = osd_dt_obj(dt);
3686         struct iam_path_descr  *ipd;
3687         struct iam_container   *bag = &obj->oo_dir->od_container;
3688         struct osd_thread_info *oti = osd_oti_get(env);
3689         struct iam_iterator    *it = &oti->oti_idx_it;
3690         struct iam_rec         *iam_rec;
3691         int                     rc;
3692
3693         ENTRY;
3694
3695         LASSERT(osd_invariant(obj));
3696         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3697         LASSERT(bag->ic_object == obj->oo_inode);
3698
3699         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
3700                 RETURN(-EACCES);
3701
3702         ipd = osd_idx_ipd_get(env, bag);
3703         if (IS_ERR(ipd))
3704                 RETURN(-ENOMEM);
3705
3706         /* got ipd now we can start iterator. */
3707         iam_it_init(it, bag, 0, ipd);
3708
3709         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3710                 /* swab quota uid/gid provided by caller */
3711                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3712                 key = (const struct dt_key *)&oti->oti_quota_id;
3713         }
3714
3715         rc = iam_it_get(it, (struct iam_key *)key);
3716         if (rc >= 0) {
3717                 if (S_ISDIR(obj->oo_inode->i_mode))
3718                         iam_rec = (struct iam_rec *)oti->oti_ldp;
3719                 else
3720                         iam_rec = (struct iam_rec *) rec;
3721
3722                 iam_reccpy(&it->ii_path.ip_leaf, (struct iam_rec *)iam_rec);
3723
3724                 if (S_ISDIR(obj->oo_inode->i_mode))
3725                         osd_fid_unpack((struct lu_fid *) rec,
3726                                        (struct osd_fid_pack *)iam_rec);
3727                 else if (fid_is_quota(lu_object_fid(&dt->do_lu)))
3728                         osd_quota_unpack(obj, rec);
3729         }
3730
3731         iam_it_put(it);
3732         iam_it_fini(it);
3733         osd_ipd_put(env, bag, ipd);
3734
3735         LINVRNT(osd_invariant(obj));
3736
3737         RETURN(rc);
3738 }
3739
3740 static int osd_index_declare_iam_insert(const struct lu_env *env,
3741                                         struct dt_object *dt,
3742                                         const struct dt_rec *rec,
3743                                         const struct dt_key *key,
3744                                         struct thandle *handle)
3745 {
3746         struct osd_thandle *oh;
3747
3748         LASSERT(handle != NULL);
3749
3750         oh = container_of0(handle, struct osd_thandle, ot_super);
3751         LASSERT(oh->ot_handle == NULL);
3752
3753         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3754                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
3755
3756         return 0;
3757 }
3758
3759 /**
3760  *      Inserts (key, value) pair in \a dt index object.
3761  *
3762  *      \param  dt      osd index object
3763  *      \param  key     key for index
3764  *      \param  rec     record reference
3765  *      \param  th      transaction handler
3766  *
3767  *      \retval  0  success
3768  *      \retval -ve failure
3769  */
3770 static int osd_index_iam_insert(const struct lu_env *env, struct dt_object *dt,
3771                                 const struct dt_rec *rec,
3772                                 const struct dt_key *key, struct thandle *th,
3773                                 struct lustre_capa *capa, int ignore_quota)
3774 {
3775         struct osd_object     *obj = osd_dt_obj(dt);
3776         struct iam_path_descr *ipd;
3777         struct osd_thandle    *oh;
3778         struct iam_container  *bag = &obj->oo_dir->od_container;
3779         struct osd_thread_info *oti = osd_oti_get(env);
3780         struct iam_rec         *iam_rec;
3781         int                     rc;
3782
3783         ENTRY;
3784
3785         LINVRNT(osd_invariant(obj));
3786         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3787         LASSERT(bag->ic_object == obj->oo_inode);
3788         LASSERT(th != NULL);
3789
3790         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
3791                 RETURN(-EACCES);
3792
3793         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3794
3795         ipd = osd_idx_ipd_get(env, bag);
3796         if (unlikely(ipd == NULL))
3797                 RETURN(-ENOMEM);
3798
3799         oh = container_of0(th, struct osd_thandle, ot_super);
3800         LASSERT(oh->ot_handle != NULL);
3801         LASSERT(oh->ot_handle->h_transaction != NULL);
3802         if (S_ISDIR(obj->oo_inode->i_mode)) {
3803                 iam_rec = (struct iam_rec *)oti->oti_ldp;
3804                 osd_fid_pack((struct osd_fid_pack *)iam_rec, rec, &oti->oti_fid);
3805         } else if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3806                 /* pack quota uid/gid */
3807                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3808                 key = (const struct dt_key *)&oti->oti_quota_id;
3809                 /* pack quota record */
3810                 rec = osd_quota_pack(obj, rec, &oti->oti_quota_rec);
3811                 iam_rec = (struct iam_rec *)rec;
3812         } else {
3813                 iam_rec = (struct iam_rec *)rec;
3814         }
3815
3816         rc = iam_insert(oh->ot_handle, bag, (const struct iam_key *)key,
3817                         iam_rec, ipd);
3818         osd_ipd_put(env, bag, ipd);
3819         LINVRNT(osd_invariant(obj));
3820         RETURN(rc);
3821 }
3822
3823 /**
3824  * Calls ldiskfs_add_entry() to add directory entry
3825  * into the directory. This is required for
3826  * interoperability mode (b11826)
3827  *
3828  * \retval   0, on success
3829  * \retval -ve, on error
3830  */
3831 static int __osd_ea_add_rec(struct osd_thread_info *info,
3832                             struct osd_object *pobj, struct inode  *cinode,
3833                             const char *name, const struct dt_rec *fid,
3834                             struct htree_lock *hlock, struct thandle *th)
3835 {
3836         struct ldiskfs_dentry_param *ldp;
3837         struct dentry               *child;
3838         struct osd_thandle          *oth;
3839         int                          rc;
3840
3841         oth = container_of(th, struct osd_thandle, ot_super);
3842         LASSERT(oth->ot_handle != NULL);
3843         LASSERT(oth->ot_handle->h_transaction != NULL);
3844         LASSERT(pobj->oo_inode);
3845
3846         ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
3847         if (unlikely(pobj->oo_inode ==
3848                      osd_sb(osd_obj2dev(pobj))->s_root->d_inode))
3849                 ldp->edp_magic = 0;
3850         else
3851                 osd_get_ldiskfs_dirent_param(ldp, fid);
3852         child = osd_child_dentry_get(info->oti_env, pobj, name, strlen(name));
3853         child->d_fsdata = (void *)ldp;
3854         ll_vfs_dq_init(pobj->oo_inode);
3855         rc = osd_ldiskfs_add_entry(oth->ot_handle, child, cinode, hlock);
3856
3857         RETURN(rc);
3858 }
3859
3860 /**
3861  * Calls ldiskfs_add_dot_dotdot() to add dot and dotdot entries
3862  * into the directory.Also sets flags into osd object to
3863  * indicate dot and dotdot are created. This is required for
3864  * interoperability mode (b11826)
3865  *
3866  * \param dir   directory for dot and dotdot fixup.
3867  * \param obj   child object for linking
3868  *
3869  * \retval   0, on success
3870  * \retval -ve, on error
3871  */
3872 static int osd_add_dot_dotdot(struct osd_thread_info *info,
3873                               struct osd_object *dir,
3874                               struct inode  *parent_dir, const char *name,
3875                               const struct dt_rec *dot_fid,
3876                               const struct dt_rec *dot_dot_fid,
3877                               struct thandle *th)
3878 {
3879         struct inode                *inode = dir->oo_inode;
3880         struct osd_thandle          *oth;
3881         int result = 0;
3882
3883         oth = container_of(th, struct osd_thandle, ot_super);
3884         LASSERT(oth->ot_handle->h_transaction != NULL);
3885         LASSERT(S_ISDIR(dir->oo_inode->i_mode));
3886
3887         if (strcmp(name, dot) == 0) {
3888                 if (dir->oo_compat_dot_created) {
3889                         result = -EEXIST;
3890                 } else {
3891                         LASSERT(inode == parent_dir);
3892                         dir->oo_compat_dot_created = 1;
3893                         result = 0;
3894                 }
3895         } else if (strcmp(name, dotdot) == 0) {
3896                 if (!dir->oo_compat_dot_created)
3897                         return -EINVAL;
3898                 /* in case of rename, dotdot is already created */
3899                 if (dir->oo_compat_dotdot_created) {
3900                         return __osd_ea_add_rec(info, dir, parent_dir, name,
3901                                                 dot_dot_fid, NULL, th);
3902                 }
3903
3904                 result = osd_add_dot_dotdot_internal(info, dir->oo_inode,
3905                                                 parent_dir, dot_fid,
3906                                                 dot_dot_fid, oth);
3907                 if (result == 0)
3908                         dir->oo_compat_dotdot_created = 1;
3909         }
3910
3911         return result;
3912 }
3913
3914
3915 /**
3916  * It will call the appropriate osd_add* function and return the
3917  * value, return by respective functions.
3918  */
3919 static int osd_ea_add_rec(const struct lu_env *env, struct osd_object *pobj,
3920                           struct inode *cinode, const char *name,
3921                           const struct dt_rec *fid, struct thandle *th)
3922 {
3923         struct osd_thread_info *info   = osd_oti_get(env);
3924         struct htree_lock      *hlock;
3925         int                     rc;
3926
3927         hlock = pobj->oo_hl_head != NULL ? info->oti_hlock : NULL;
3928
3929         if (name[0] == '.' && (name[1] == '\0' || (name[1] == '.' &&
3930                                                    name[2] =='\0'))) {
3931                 if (hlock != NULL) {
3932                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
3933                                            pobj->oo_inode, 0);
3934                 } else {
3935                         down_write(&pobj->oo_ext_idx_sem);
3936                 }
3937                 rc = osd_add_dot_dotdot(info, pobj, cinode, name,
3938                      (struct dt_rec *)lu_object_fid(&pobj->oo_dt.do_lu),
3939                                         fid, th);
3940         } else {
3941                 if (hlock != NULL) {
3942                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
3943                                            pobj->oo_inode, LDISKFS_HLOCK_ADD);
3944                 } else {
3945                         down_write(&pobj->oo_ext_idx_sem);
3946                 }
3947
3948                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_INDIR)) {
3949                         struct lu_fid *tfid = &info->oti_fid;
3950
3951                         *tfid = *(const struct lu_fid *)fid;
3952                         tfid->f_ver = ~0;
3953                         rc = __osd_ea_add_rec(info, pobj, cinode, name,
3954                                               (const struct dt_rec *)tfid,
3955                                               hlock, th);
3956                 } else {
3957                         rc = __osd_ea_add_rec(info, pobj, cinode, name, fid,
3958                                               hlock, th);
3959                 }
3960         }
3961         if (hlock != NULL)
3962                 ldiskfs_htree_unlock(hlock);
3963         else
3964                 up_write(&pobj->oo_ext_idx_sem);
3965
3966         return rc;
3967 }
3968
3969 static void
3970 osd_consistency_check(struct osd_thread_info *oti, struct osd_device *dev,
3971                       struct osd_idmap_cache *oic)
3972 {
3973         struct osd_scrub    *scrub = &dev->od_scrub;
3974         struct lu_fid       *fid   = &oic->oic_fid;
3975         struct osd_inode_id *id    = &oti->oti_id;
3976         int                  once  = 0;
3977         int                  rc;
3978         ENTRY;
3979
3980         if (!fid_is_norm(fid) && !fid_is_igif(fid))
3981                 RETURN_EXIT;
3982
3983 again:
3984         rc = osd_oi_lookup(oti, dev, fid, id, OI_CHECK_FLD);
3985         if (rc != 0 && rc != -ENOENT)
3986                 RETURN_EXIT;
3987
3988         if (rc == 0 && osd_id_eq(id, &oic->oic_lid))
3989                 RETURN_EXIT;
3990
3991         if (thread_is_running(&scrub->os_thread)) {
3992                 rc = osd_oii_insert(dev, oic, rc == -ENOENT);
3993                 /* There is race condition between osd_oi_lookup and OI scrub.
3994                  * The OI scrub finished just after osd_oi_lookup() failure.
3995                  * Under such case, it is unnecessary to trigger OI scrub again,
3996                  * but try to call osd_oi_lookup() again. */
3997                 if (unlikely(rc == -EAGAIN))
3998                         goto again;
3999
4000                 RETURN_EXIT;
4001         }
4002
4003         if (!dev->od_noscrub && ++once == 1) {
4004                 rc = osd_scrub_start(dev);
4005                 LCONSOLE_WARN("%.16s: trigger OI scrub by RPC for "DFID
4006                               ", rc = %d [2]\n",
4007                               LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name,
4008                               PFID(fid), rc);
4009                 if (rc == 0)
4010                         goto again;
4011         }
4012
4013         EXIT;
4014 }
4015
4016 static int osd_fail_fid_lookup(struct osd_thread_info *oti,
4017                                struct osd_device *dev,
4018                                struct osd_idmap_cache *oic,
4019                                struct lu_fid *fid, __u32 ino)
4020 {
4021         struct lustre_mdt_attrs *lma   = &oti->oti_mdt_attrs;
4022         struct inode            *inode;
4023         int                      rc;
4024
4025         osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
4026         inode = osd_iget(oti, dev, &oic->oic_lid);
4027         if (IS_ERR(inode)) {
4028                 fid_zero(&oic->oic_fid);
4029                 return PTR_ERR(inode);
4030         }
4031
4032         rc = osd_get_lma(oti, inode, &oti->oti_obj_dentry, lma);
4033         iput(inode);
4034         if (rc != 0)
4035                 fid_zero(&oic->oic_fid);
4036         else
4037                 *fid = oic->oic_fid = lma->lma_self_fid;
4038         return rc;
4039 }
4040
4041 int osd_add_oi_cache(struct osd_thread_info *info, struct osd_device *osd,
4042                      struct osd_inode_id *id, const struct lu_fid *fid)
4043 {
4044         CDEBUG(D_INODE, "add "DFID" %u:%u to info %p\n", PFID(fid),
4045                id->oii_ino, id->oii_gen, info);
4046         info->oti_cache.oic_lid = *id;
4047         info->oti_cache.oic_fid = *fid;
4048         info->oti_cache.oic_dev = osd;
4049
4050         return 0;
4051 }
4052
4053 /**
4054  * Calls ->lookup() to find dentry. From dentry get inode and
4055  * read inode's ea to get fid. This is required for  interoperability
4056  * mode (b11826)
4057  *
4058  * \retval   0, on success
4059  * \retval -ve, on error
4060  */
4061 static int osd_ea_lookup_rec(const struct lu_env *env, struct osd_object *obj,
4062                              struct dt_rec *rec, const struct dt_key *key)
4063 {
4064         struct inode               *dir    = obj->oo_inode;
4065         struct dentry              *dentry;
4066         struct ldiskfs_dir_entry_2 *de;
4067         struct buffer_head         *bh;
4068         struct lu_fid              *fid = (struct lu_fid *) rec;
4069         struct htree_lock          *hlock = NULL;
4070         int                         ino;
4071         int                         rc;
4072         ENTRY;
4073
4074         LASSERT(dir->i_op != NULL && dir->i_op->lookup != NULL);
4075
4076         dentry = osd_child_dentry_get(env, obj,
4077                                       (char *)key, strlen((char *)key));
4078
4079         if (obj->oo_hl_head != NULL) {
4080                 hlock = osd_oti_get(env)->oti_hlock;
4081                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
4082                                    dir, LDISKFS_HLOCK_LOOKUP);
4083         } else {
4084                 down_read(&obj->oo_ext_idx_sem);
4085         }
4086
4087         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
4088         if (bh) {
4089                 struct osd_thread_info *oti = osd_oti_get(env);
4090                 struct osd_inode_id *id = &oti->oti_id;
4091                 struct osd_idmap_cache *oic = &oti->oti_cache;
4092                 struct osd_device *dev = osd_obj2dev(obj);
4093                 struct osd_scrub *scrub = &dev->od_scrub;
4094                 struct scrub_file *sf = &scrub->os_file;
4095
4096                 ino = le32_to_cpu(de->inode);
4097                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP)) {
4098                         brelse(bh);
4099                         rc = osd_fail_fid_lookup(oti, dev, oic, fid, ino);
4100                         GOTO(out, rc);
4101                 }
4102
4103                 rc = osd_get_fid_from_dentry(de, rec);
4104
4105                 /* done with de, release bh */
4106                 brelse(bh);
4107                 if (rc != 0)
4108                         rc = osd_ea_fid_get(env, obj, ino, fid, id);
4109                 else
4110                         osd_id_gen(id, ino, OSD_OII_NOGEN);
4111                 if (rc != 0) {
4112                         fid_zero(&oic->oic_fid);
4113                         GOTO(out, rc);
4114                 }
4115
4116                 if (osd_remote_fid(env, dev, fid))
4117                         GOTO(out, rc = 0);
4118
4119                 rc = osd_add_oi_cache(osd_oti_get(env), osd_obj2dev(obj), id,
4120                                       fid);
4121                 if (rc != 0)
4122                         GOTO(out, rc);
4123                 if ((scrub->os_pos_current <= ino) &&
4124                     ((sf->sf_flags & SF_INCONSISTENT) ||
4125                      (sf->sf_flags & SF_UPGRADE && fid_is_igif(fid)) ||
4126                      ldiskfs_test_bit(osd_oi_fid2idx(dev, fid),
4127                                       sf->sf_oi_bitmap)))
4128                         osd_consistency_check(oti, dev, oic);
4129         } else {
4130                 rc = -ENOENT;
4131         }
4132
4133         GOTO(out, rc);
4134
4135 out:
4136         if (hlock != NULL)
4137                 ldiskfs_htree_unlock(hlock);
4138         else
4139                 up_read(&obj->oo_ext_idx_sem);
4140         return rc;
4141 }
4142
4143 /**
4144  * Find the osd object for given fid.
4145  *
4146  * \param fid need to find the osd object having this fid
4147  *
4148  * \retval osd_object on success
4149  * \retval        -ve on error
4150  */
4151 struct osd_object *osd_object_find(const struct lu_env *env,
4152                                    struct dt_object *dt,
4153                                    const struct lu_fid *fid)
4154 {
4155         struct lu_device  *ludev = dt->do_lu.lo_dev;
4156         struct osd_object *child = NULL;
4157         struct lu_object  *luch;
4158         struct lu_object  *lo;
4159
4160         /*
4161          * at this point topdev might not exist yet
4162          * (i.e. MGS is preparing profiles). so we can
4163          * not rely on topdev and instead lookup with
4164          * our device passed as topdev. this can't work
4165          * if the object isn't cached yet (as osd doesn't
4166          * allocate lu_header). IOW, the object must be
4167          * in the cache, otherwise lu_object_alloc() crashes
4168          * -bzzz
4169          */
4170         luch = lu_object_find_at(env, ludev, fid, NULL);
4171         if (!IS_ERR(luch)) {
4172                 if (lu_object_exists(luch)) {
4173                         lo = lu_object_locate(luch->lo_header, ludev->ld_type);
4174                         if (lo != NULL)
4175                                 child = osd_obj(lo);
4176                         else
4177                                 LU_OBJECT_DEBUG(D_ERROR, env, luch,
4178                                                 "lu_object can't be located"
4179                                                 DFID"\n", PFID(fid));
4180
4181                         if (child == NULL) {
4182                                 lu_object_put(env, luch);
4183                                 CERROR("Unable to get osd_object\n");
4184                                 child = ERR_PTR(-ENOENT);
4185                         }
4186                 } else {
4187                         LU_OBJECT_DEBUG(D_ERROR, env, luch,
4188                                         "lu_object does not exists "DFID"\n",
4189                                         PFID(fid));
4190                         lu_object_put(env, luch);
4191                         child = ERR_PTR(-ENOENT);
4192                 }
4193         } else {
4194                 child = ERR_CAST(luch);
4195         }
4196
4197         return child;
4198 }
4199
4200 /**
4201  * Put the osd object once done with it.
4202  *
4203  * \param obj osd object that needs to be put
4204  */
4205 static inline void osd_object_put(const struct lu_env *env,
4206                                   struct osd_object *obj)
4207 {
4208         lu_object_put(env, &obj->oo_dt.do_lu);
4209 }
4210
4211 static int osd_index_declare_ea_insert(const struct lu_env *env,
4212                                        struct dt_object *dt,
4213                                        const struct dt_rec *rec,
4214                                        const struct dt_key *key,
4215                                        struct thandle *handle)
4216 {
4217         struct osd_thandle      *oh;
4218         struct osd_device       *osd   = osd_dev(dt->do_lu.lo_dev);
4219         struct lu_fid           *fid = (struct lu_fid *)rec;
4220         int                     rc;
4221         ENTRY;
4222
4223         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
4224         LASSERT(handle != NULL);
4225
4226         oh = container_of0(handle, struct osd_thandle, ot_super);
4227         LASSERT(oh->ot_handle == NULL);
4228
4229         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4230                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
4231
4232         if (osd_dt_obj(dt)->oo_inode == NULL) {
4233                 const char *name  = (const char *)key;
4234                 /* Object is not being created yet. Only happens when
4235                  *     1. declare directory create
4236                  *     2. declare insert .
4237                  *     3. declare insert ..
4238                  */
4239                 LASSERT(strcmp(name, dotdot) == 0 || strcmp(name, dot) == 0);
4240         } else {
4241                 struct inode *inode = osd_dt_obj(dt)->oo_inode;
4242
4243                 /* We ignore block quota on meta pool (MDTs), so needn't
4244                  * calculate how many blocks will be consumed by this index
4245                  * insert */
4246                 rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0,
4247                                            oh, true, true, NULL, false);
4248         }
4249
4250         if (fid == NULL)
4251                 RETURN(0);
4252
4253         rc = osd_remote_fid(env, osd, fid);
4254         if (rc <= 0)
4255                 RETURN(rc);
4256
4257         rc = 0;
4258
4259         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
4260                              osd_dto_credits_noquota[DTO_OBJECT_CREATE]);
4261         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4262                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
4263         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4264                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
4265
4266         RETURN(rc);
4267 }
4268
4269 /**
4270  * Index add function for interoperability mode (b11826).
4271  * It will add the directory entry.This entry is needed to
4272  * maintain name->fid mapping.
4273  *
4274  * \param key it is key i.e. file entry to be inserted
4275  * \param rec it is value of given key i.e. fid
4276  *
4277  * \retval   0, on success
4278  * \retval -ve, on error
4279  */
4280 static int osd_index_ea_insert(const struct lu_env *env, struct dt_object *dt,
4281                                const struct dt_rec *rec,
4282                                const struct dt_key *key, struct thandle *th,
4283                                struct lustre_capa *capa, int ignore_quota)
4284 {
4285         struct osd_object       *obj = osd_dt_obj(dt);
4286         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
4287         struct lu_fid           *fid = (struct lu_fid *) rec;
4288         const char              *name = (const char *)key;
4289         struct osd_thread_info  *oti   = osd_oti_get(env);
4290         struct osd_inode_id     *id    = &oti->oti_id;
4291         struct inode            *child_inode = NULL;
4292         struct osd_object       *child = NULL;
4293         int                     rc;
4294         ENTRY;
4295
4296         LASSERT(osd_invariant(obj));
4297         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
4298         LASSERT(th != NULL);
4299
4300         osd_trans_exec_op(env, th, OSD_OT_INSERT);
4301
4302         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
4303                 RETURN(-EACCES);
4304
4305         LASSERTF(fid_is_sane(fid), "fid"DFID" is insane!", PFID(fid));
4306
4307         rc = osd_remote_fid(env, osd, fid);
4308         if (rc < 0) {
4309                 CERROR("%s: Can not find object "DFID" rc %d\n",
4310                        osd_name(osd), PFID(fid), rc);
4311                 RETURN(rc);
4312         }
4313
4314         if (rc == 1) {
4315                 /* Insert remote entry */
4316                 if (strcmp(name, dotdot) == 0 && strlen(name) == 2) {
4317                         struct osd_mdobj_map    *omm = osd->od_mdt_map;
4318                         struct osd_thandle      *oh;
4319
4320                         /* If parent on remote MDT, we need put this object
4321                          * under AGENT */
4322                         oh = container_of(th, typeof(*oh), ot_super);
4323                         rc = osd_add_to_remote_parent(env, osd, obj, oh);
4324                         if (rc != 0) {
4325                                 CERROR("%s: add "DFID" error: rc = %d\n",
4326                                        osd_name(osd),
4327                                        PFID(lu_object_fid(&dt->do_lu)), rc);
4328                                 RETURN(rc);
4329                         }
4330
4331                         child_inode = igrab(omm->omm_remote_parent->d_inode);
4332                 } else {
4333                         child_inode = osd_create_local_agent_inode(env, osd,
4334                                                                    obj, fid,
4335                                                                    th);
4336                         if (IS_ERR(child_inode))
4337                                 RETURN(PTR_ERR(child_inode));
4338                 }
4339         } else {
4340                 /* Insert local entry */
4341                 child = osd_object_find(env, dt, fid);
4342                 if (IS_ERR(child)) {
4343                         CERROR("%s: Can not find object "DFID"%u:%u: rc = %d\n",
4344                                osd_name(osd), PFID(fid),
4345                                id->oii_ino, id->oii_gen,
4346                                (int)PTR_ERR(child));
4347                         RETURN(PTR_ERR(child));
4348                 }
4349                 child_inode = igrab(child->oo_inode);
4350         }
4351
4352         rc = osd_ea_add_rec(env, obj, child_inode, name, rec, th);
4353
4354         iput(child_inode);
4355         if (child != NULL)
4356                 osd_object_put(env, child);
4357         LASSERT(osd_invariant(obj));
4358         RETURN(rc);
4359 }
4360
4361 /**
4362  *  Initialize osd Iterator for given osd index object.
4363  *
4364  *  \param  dt      osd index object
4365  */
4366
4367 static struct dt_it *osd_it_iam_init(const struct lu_env *env,
4368                                      struct dt_object *dt,
4369                                      __u32 unused,
4370                                      struct lustre_capa *capa)
4371 {
4372         struct osd_it_iam      *it;
4373         struct osd_thread_info *oti = osd_oti_get(env);
4374         struct osd_object      *obj = osd_dt_obj(dt);
4375         struct lu_object       *lo  = &dt->do_lu;
4376         struct iam_path_descr  *ipd;
4377         struct iam_container   *bag = &obj->oo_dir->od_container;
4378
4379         LASSERT(lu_object_exists(lo));
4380
4381         if (osd_object_auth(env, dt, capa, CAPA_OPC_BODY_READ))
4382                 return ERR_PTR(-EACCES);
4383
4384         it = &oti->oti_it;
4385         ipd = osd_it_ipd_get(env, bag);
4386         if (likely(ipd != NULL)) {
4387                 it->oi_obj = obj;
4388                 it->oi_ipd = ipd;
4389                 lu_object_get(lo);
4390                 iam_it_init(&it->oi_it, bag, IAM_IT_MOVE, ipd);
4391                 return (struct dt_it *)it;
4392         }
4393         return ERR_PTR(-ENOMEM);
4394 }
4395
4396 /**
4397  * free given Iterator.
4398  */
4399
4400 static void osd_it_iam_fini(const struct lu_env *env, struct dt_it *di)
4401 {
4402         struct osd_it_iam *it = (struct osd_it_iam *)di;
4403         struct osd_object *obj = it->oi_obj;
4404
4405         iam_it_fini(&it->oi_it);
4406         osd_ipd_put(env, &obj->oo_dir->od_container, it->oi_ipd);
4407         lu_object_put(env, &obj->oo_dt.do_lu);
4408 }
4409
4410 /**
4411  *  Move Iterator to record specified by \a key
4412  *
4413  *  \param  di      osd iterator
4414  *  \param  key     key for index
4415  *
4416  *  \retval +ve  di points to record with least key not larger than key
4417  *  \retval  0   di points to exact matched key
4418  *  \retval -ve  failure
4419  */
4420
4421 static int osd_it_iam_get(const struct lu_env *env,
4422                           struct dt_it *di, const struct dt_key *key)
4423 {
4424         struct osd_thread_info  *oti = osd_oti_get(env);
4425         struct osd_it_iam       *it = (struct osd_it_iam *)di;
4426
4427         if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
4428                 /* swab quota uid/gid */
4429                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
4430                 key = (struct dt_key *)&oti->oti_quota_id;
4431         }
4432
4433         return iam_it_get(&it->oi_it, (const struct iam_key *)key);
4434 }
4435
4436 /**
4437  *  Release Iterator
4438  *
4439  *  \param  di      osd iterator
4440  */
4441 static void osd_it_iam_put(const struct lu_env *env, struct dt_it *di)
4442 {
4443         struct osd_it_iam *it = (struct osd_it_iam *)di;
4444
4445         iam_it_put(&it->oi_it);
4446 }
4447
4448 /**
4449  *  Move iterator by one record
4450  *
4451  *  \param  di      osd iterator
4452  *
4453  *  \retval +1   end of container reached
4454  *  \retval  0   success
4455  *  \retval -ve  failure
4456  */
4457
4458 static int osd_it_iam_next(const struct lu_env *env, struct dt_it *di)
4459 {
4460         struct osd_it_iam *it = (struct osd_it_iam *)di;
4461
4462         return iam_it_next(&it->oi_it);
4463 }
4464
4465 /**
4466  * Return pointer to the key under iterator.
4467  */
4468
4469 static struct dt_key *osd_it_iam_key(const struct lu_env *env,
4470                                  const struct dt_it *di)
4471 {
4472         struct osd_thread_info *oti = osd_oti_get(env);
4473         struct osd_it_iam      *it = (struct osd_it_iam *)di;
4474         struct osd_object      *obj = it->oi_obj;
4475         struct dt_key          *key;
4476
4477         key = (struct dt_key *)iam_it_key_get(&it->oi_it);
4478
4479         if (!IS_ERR(key) && fid_is_quota(lu_object_fid(&obj->oo_dt.do_lu))) {
4480                 /* swab quota uid/gid */
4481                 oti->oti_quota_id = le64_to_cpu(*((__u64 *)key));
4482                 key = (struct dt_key *)&oti->oti_quota_id;
4483         }
4484
4485         return key;
4486 }
4487
4488 /**
4489  * Return size of key under iterator (in bytes)
4490  */
4491
4492 static int osd_it_iam_key_size(const struct lu_env *env, const struct dt_it *di)
4493 {
4494         struct osd_it_iam *it = (struct osd_it_iam *)di;
4495
4496         return iam_it_key_size(&it->oi_it);
4497 }
4498
4499 static inline void
4500 osd_it_append_attrs(struct lu_dirent *ent, int len, __u16 type)
4501 {
4502         /* check if file type is required */
4503         if (ent->lde_attrs & LUDA_TYPE) {
4504                 struct luda_type *lt;
4505                 int align = sizeof(*lt) - 1;
4506
4507                 len = (len + align) & ~align;
4508                 lt = (struct luda_type *)(ent->lde_name + len);
4509                 lt->lt_type = cpu_to_le16(DTTOIF(type));
4510         }
4511
4512         ent->lde_attrs = cpu_to_le32(ent->lde_attrs);
4513 }
4514
4515 /**
4516  * build lu direct from backend fs dirent.
4517  */
4518
4519 static inline void
4520 osd_it_pack_dirent(struct lu_dirent *ent, struct lu_fid *fid, __u64 offset,
4521                    char *name, __u16 namelen, __u16 type, __u32 attr)
4522 {
4523         ent->lde_attrs = attr | LUDA_FID;
4524         fid_cpu_to_le(&ent->lde_fid, fid);
4525
4526         ent->lde_hash = cpu_to_le64(offset);
4527         ent->lde_reclen = cpu_to_le16(lu_dirent_calc_size(namelen, attr));
4528
4529         strncpy(ent->lde_name, name, namelen);
4530         ent->lde_name[namelen] = '\0';
4531         ent->lde_namelen = cpu_to_le16(namelen);
4532
4533         /* append lustre attributes */
4534         osd_it_append_attrs(ent, namelen, type);
4535 }
4536
4537 /**
4538  * Return pointer to the record under iterator.
4539  */
4540 static int osd_it_iam_rec(const struct lu_env *env,
4541                           const struct dt_it *di,
4542                           struct dt_rec *dtrec, __u32 attr)
4543 {
4544         struct osd_it_iam      *it   = (struct osd_it_iam *)di;
4545         struct osd_thread_info *info = osd_oti_get(env);
4546         ENTRY;
4547
4548         if (S_ISDIR(it->oi_obj->oo_inode->i_mode)) {
4549                 const struct osd_fid_pack *rec;
4550                 struct lu_fid             *fid = &info->oti_fid;
4551                 struct lu_dirent          *lde = (struct lu_dirent *)dtrec;
4552                 char                      *name;
4553                 int                        namelen;
4554                 __u64                      hash;
4555                 int                        rc;
4556
4557                 name = (char *)iam_it_key_get(&it->oi_it);
4558                 if (IS_ERR(name))
4559                         RETURN(PTR_ERR(name));
4560
4561                 namelen = iam_it_key_size(&it->oi_it);
4562
4563                 rec = (const struct osd_fid_pack *)iam_it_rec_get(&it->oi_it);
4564                 if (IS_ERR(rec))
4565                         RETURN(PTR_ERR(rec));
4566
4567                 rc = osd_fid_unpack(fid, rec);
4568                 if (rc)
4569                         RETURN(rc);
4570
4571                 hash = iam_it_store(&it->oi_it);
4572
4573                 /* IAM does not store object type in IAM index (dir) */
4574                 osd_it_pack_dirent(lde, fid, hash, name, namelen,
4575                                    0, LUDA_FID);
4576         } else if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
4577                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
4578                            (struct iam_rec *)dtrec);
4579                 osd_quota_unpack(it->oi_obj, dtrec);
4580         } else {
4581                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
4582                            (struct iam_rec *)dtrec);
4583         }
4584
4585         RETURN(0);
4586 }
4587
4588 /**
4589  * Returns cookie for current Iterator position.
4590  */
4591 static __u64 osd_it_iam_store(const struct lu_env *env, const struct dt_it *di)
4592 {
4593         struct osd_it_iam *it = (struct osd_it_iam *)di;
4594
4595         return iam_it_store(&it->oi_it);
4596 }
4597
4598 /**
4599  * Restore iterator from cookie.
4600  *
4601  * \param  di      osd iterator
4602  * \param  hash    Iterator location cookie
4603  *
4604  * \retval +ve  di points to record with least key not larger than key.
4605  * \retval  0   di points to exact matched key
4606  * \retval -ve  failure
4607  */
4608
4609 static int osd_it_iam_load(const struct lu_env *env,
4610                            const struct dt_it *di, __u64 hash)
4611 {
4612         struct osd_it_iam *it = (struct osd_it_iam *)di;
4613
4614         return iam_it_load(&it->oi_it, hash);
4615 }
4616
4617 static const struct dt_index_operations osd_index_iam_ops = {
4618         .dio_lookup         = osd_index_iam_lookup,
4619         .dio_declare_insert = osd_index_declare_iam_insert,
4620         .dio_insert         = osd_index_iam_insert,
4621         .dio_declare_delete = osd_index_declare_iam_delete,
4622         .dio_delete         = osd_index_iam_delete,
4623         .dio_it     = {
4624                 .init     = osd_it_iam_init,
4625                 .fini     = osd_it_iam_fini,
4626                 .get      = osd_it_iam_get,
4627                 .put      = osd_it_iam_put,
4628                 .next     = osd_it_iam_next,
4629                 .key      = osd_it_iam_key,
4630                 .key_size = osd_it_iam_key_size,
4631                 .rec      = osd_it_iam_rec,
4632                 .store    = osd_it_iam_store,
4633                 .load     = osd_it_iam_load
4634         }
4635 };
4636
4637
4638 /**
4639  * Creates or initializes iterator context.
4640  *
4641  * \retval struct osd_it_ea, iterator structure on success
4642  *
4643  */
4644 static struct dt_it *osd_it_ea_init(const struct lu_env *env,
4645                                     struct dt_object *dt,
4646                                     __u32 attr,
4647                                     struct lustre_capa *capa)
4648 {
4649         struct osd_object       *obj  = osd_dt_obj(dt);
4650         struct osd_thread_info  *info = osd_oti_get(env);
4651         struct osd_it_ea        *it   = &info->oti_it_ea;
4652         struct file             *file = &it->oie_file;
4653         struct lu_object        *lo   = &dt->do_lu;
4654         struct dentry           *obj_dentry = &info->oti_it_dentry;
4655         ENTRY;
4656         LASSERT(lu_object_exists(lo));
4657
4658         obj_dentry->d_inode = obj->oo_inode;
4659         obj_dentry->d_sb = osd_sb(osd_obj2dev(obj));
4660         obj_dentry->d_name.hash = 0;
4661
4662         it->oie_rd_dirent       = 0;
4663         it->oie_it_dirent       = 0;
4664         it->oie_dirent          = NULL;
4665         it->oie_buf             = info->oti_it_ea_buf;
4666         it->oie_obj             = obj;
4667
4668         /* Reset the "file" totally to avoid to reuse any old value from
4669          * former readdir handling, the "file->f_pos" should be zero. */
4670         memset(file, 0, sizeof(*file));
4671         /* Only FMODE_64BITHASH or FMODE_32BITHASH should be set, NOT both. */
4672         if (attr & LUDA_64BITHASH)
4673                 file->f_mode    = FMODE_64BITHASH;
4674         else
4675                 file->f_mode    = FMODE_32BITHASH;
4676         file->f_dentry          = obj_dentry;
4677         file->f_mapping         = obj->oo_inode->i_mapping;
4678         file->f_op              = obj->oo_inode->i_fop;
4679         set_file_inode(file, obj->oo_inode);
4680
4681         lu_object_get(lo);
4682         RETURN((struct dt_it *) it);
4683 }
4684
4685 /**
4686  * Destroy or finishes iterator context.
4687  *
4688  * \param di iterator structure to be destroyed
4689  */
4690 static void osd_it_ea_fini(const struct lu_env *env, struct dt_it *di)
4691 {
4692         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
4693         struct osd_object    *obj  = it->oie_obj;
4694         struct inode       *inode  = obj->oo_inode;
4695
4696         ENTRY;
4697         it->oie_file.f_op->release(inode, &it->oie_file);
4698         lu_object_put(env, &obj->oo_dt.do_lu);
4699         EXIT;
4700 }
4701
4702 /**
4703  * It position the iterator at given key, so that next lookup continues from
4704  * that key Or it is similar to dio_it->load() but based on a key,
4705  * rather than file position.
4706  *
4707  * As a special convention, osd_it_ea_get(env, di, "") has to rewind iterator
4708  * to the beginning.
4709  *
4710  * TODO: Presently return +1 considering it is only used by mdd_dir_is_empty().
4711  */
4712 static int osd_it_ea_get(const struct lu_env *env,
4713                          struct dt_it *di, const struct dt_key *key)
4714 {
4715         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
4716
4717         ENTRY;
4718         LASSERT(((const char *)key)[0] == '\0');
4719         it->oie_file.f_pos      = 0;
4720         it->oie_rd_dirent       = 0;
4721         it->oie_it_dirent       = 0;
4722         it->oie_dirent          = NULL;
4723
4724         RETURN(+1);
4725 }
4726
4727 /**
4728  * Does nothing
4729  */
4730 static void osd_it_ea_put(const struct lu_env *env, struct dt_it *di)
4731 {
4732 }
4733
4734 /**
4735  * It is called internally by ->readdir(). It fills the
4736  * iterator's in-memory data structure with required
4737  * information i.e. name, namelen, rec_size etc.
4738  *
4739  * \param buf in which information to be filled in.
4740  * \param name name of the file in given dir
4741  *
4742  * \retval 0 on success
4743  * \retval 1 on buffer full
4744  */
4745 static int osd_ldiskfs_filldir(char *buf, const char *name, int namelen,
4746                                loff_t offset, __u64 ino,
4747                                unsigned d_type)
4748 {
4749         struct osd_it_ea        *it   = (struct osd_it_ea *)buf;
4750         struct osd_object       *obj  = it->oie_obj;
4751         struct osd_it_ea_dirent *ent  = it->oie_dirent;
4752         struct lu_fid           *fid  = &ent->oied_fid;
4753         struct osd_fid_pack     *rec;
4754         ENTRY;
4755
4756         /* this should never happen */
4757         if (unlikely(namelen == 0 || namelen > LDISKFS_NAME_LEN)) {
4758                 CERROR("ldiskfs return invalid namelen %d\n", namelen);
4759                 RETURN(-EIO);
4760         }
4761
4762         if ((void *) ent - it->oie_buf + sizeof(*ent) + namelen >
4763             OSD_IT_EA_BUFSIZE)
4764                 RETURN(1);
4765
4766         /* "." is just the object itself. */
4767         if (namelen == 1 && name[0] == '.') {
4768                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
4769         } else if (d_type & LDISKFS_DIRENT_LUFID) {
4770                 rec = (struct osd_fid_pack*) (name + namelen + 1);
4771                 if (osd_fid_unpack(fid, rec) != 0)
4772                         fid_zero(fid);
4773         } else {
4774                 fid_zero(fid);
4775         }
4776         d_type &= ~LDISKFS_DIRENT_LUFID;
4777
4778         /* NOT export local root. */
4779         if (unlikely(osd_sb(osd_obj2dev(obj))->s_root->d_inode->i_ino == ino)) {
4780                 ino = obj->oo_inode->i_ino;
4781                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
4782         }
4783
4784         ent->oied_ino     = ino;
4785         ent->oied_off     = offset;
4786         ent->oied_namelen = namelen;
4787         ent->oied_type    = d_type;
4788
4789         memcpy(ent->oied_name, name, namelen);
4790
4791         it->oie_rd_dirent++;
4792         it->oie_dirent = (void *) ent + cfs_size_round(sizeof(*ent) + namelen);
4793         RETURN(0);
4794 }
4795
4796 /**
4797  * Calls ->readdir() to load a directory entry at a time
4798  * and stored it in iterator's in-memory data structure.
4799  *
4800  * \param di iterator's in memory structure
4801  *
4802  * \retval   0 on success
4803  * \retval -ve on error
4804  */
4805 static int osd_ldiskfs_it_fill(const struct lu_env *env,
4806                                const struct dt_it *di)
4807 {
4808         struct osd_it_ea   *it    = (struct osd_it_ea *)di;
4809         struct osd_object  *obj   = it->oie_obj;
4810         struct inode       *inode = obj->oo_inode;
4811         struct htree_lock  *hlock = NULL;
4812         int                 result = 0;
4813
4814         ENTRY;
4815         it->oie_dirent = it->oie_buf;
4816         it->oie_rd_dirent = 0;
4817
4818         if (obj->oo_hl_head != NULL) {
4819                 hlock = osd_oti_get(env)->oti_hlock;
4820                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
4821                                    inode, LDISKFS_HLOCK_READDIR);
4822         } else {
4823                 down_read(&obj->oo_ext_idx_sem);
4824         }
4825
4826         result = inode->i_fop->readdir(&it->oie_file, it,
4827                                        (filldir_t) osd_ldiskfs_filldir);
4828
4829         if (hlock != NULL)
4830                 ldiskfs_htree_unlock(hlock);
4831         else
4832                 up_read(&obj->oo_ext_idx_sem);
4833
4834         if (it->oie_rd_dirent == 0) {
4835                 result = -EIO;
4836         } else {
4837                 it->oie_dirent = it->oie_buf;
4838                 it->oie_it_dirent = 1;
4839         }
4840
4841         RETURN(result);
4842 }
4843
4844 /**
4845  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
4846  * to load a directory entry at a time and stored it in
4847  * iterator's in-memory data structure.
4848  *
4849  * \param di iterator's in memory structure
4850  *
4851  * \retval +ve iterator reached to end
4852  * \retval   0 iterator not reached to end
4853  * \retval -ve on error
4854  */
4855 static int osd_it_ea_next(const struct lu_env *env, struct dt_it *di)
4856 {
4857         struct osd_it_ea *it = (struct osd_it_ea *)di;
4858         int rc;
4859
4860         ENTRY;
4861
4862         if (it->oie_it_dirent < it->oie_rd_dirent) {
4863                 it->oie_dirent =
4864                         (void *) it->oie_dirent +
4865                         cfs_size_round(sizeof(struct osd_it_ea_dirent) +
4866                                        it->oie_dirent->oied_namelen);
4867                 it->oie_it_dirent++;
4868                 RETURN(0);
4869         } else {
4870                 if (it->oie_file.f_pos == ldiskfs_get_htree_eof(&it->oie_file))
4871                         rc = +1;
4872                 else
4873                         rc = osd_ldiskfs_it_fill(env, di);
4874         }
4875
4876         RETURN(rc);
4877 }
4878
4879 /**
4880  * Returns the key at current position from iterator's in memory structure.
4881  *
4882  * \param di iterator's in memory structure
4883  *
4884  * \retval key i.e. struct dt_key on success
4885  */
4886 static struct dt_key *osd_it_ea_key(const struct lu_env *env,
4887                                     const struct dt_it *di)
4888 {
4889         struct osd_it_ea *it = (struct osd_it_ea *)di;
4890
4891         return (struct dt_key *)it->oie_dirent->oied_name;
4892 }
4893
4894 /**
4895  * Returns the key's size at current position from iterator's in memory structure.
4896  *
4897  * \param di iterator's in memory structure
4898  *
4899  * \retval key_size i.e. struct dt_key on success
4900  */
4901 static int osd_it_ea_key_size(const struct lu_env *env, const struct dt_it *di)
4902 {
4903         struct osd_it_ea *it = (struct osd_it_ea *)di;
4904
4905         return it->oie_dirent->oied_namelen;
4906 }
4907
4908 static int
4909 osd_dirent_update(handle_t *jh, struct super_block *sb,
4910                   struct osd_it_ea_dirent *ent, struct lu_fid *fid,
4911                   struct buffer_head *bh, struct ldiskfs_dir_entry_2 *de)
4912 {
4913         struct osd_fid_pack *rec;
4914         int                  rc;
4915         ENTRY;
4916
4917         LASSERT(de->file_type & LDISKFS_DIRENT_LUFID);
4918         LASSERT(de->rec_len >= de->name_len + sizeof(struct osd_fid_pack));
4919
4920         rc = ldiskfs_journal_get_write_access(jh, bh);
4921         if (rc != 0) {
4922                 CERROR("%.16s: fail to write access for update dirent: "
4923                        "name = %.*s, rc = %d\n",
4924                        LDISKFS_SB(sb)->s_es->s_volume_name,
4925                        ent->oied_namelen, ent->oied_name, rc);
4926                 RETURN(rc);
4927         }
4928
4929         rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
4930         fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
4931         rc = ldiskfs_journal_dirty_metadata(jh, bh);
4932         if (rc != 0)
4933                 CERROR("%.16s: fail to dirty metadata for update dirent: "
4934                        "name = %.*s, rc = %d\n",
4935                        LDISKFS_SB(sb)->s_es->s_volume_name,
4936                        ent->oied_namelen, ent->oied_name, rc);
4937
4938         RETURN(rc);
4939 }
4940
4941 static inline int
4942 osd_dirent_has_space(__u16 reclen, __u16 namelen, unsigned blocksize)
4943 {
4944         if (ldiskfs_rec_len_from_disk(reclen, blocksize) >=
4945             __LDISKFS_DIR_REC_LEN(namelen + 1 + sizeof(struct osd_fid_pack)))
4946                 return 1;
4947         else
4948                 return 0;
4949 }
4950
4951 static inline int
4952 osd_dot_dotdot_has_space(struct ldiskfs_dir_entry_2 *de, int dot_dotdot)
4953 {
4954         LASSERTF(dot_dotdot == 1 || dot_dotdot == 2,
4955                  "dot_dotdot = %d\n", dot_dotdot);
4956
4957         if (LDISKFS_DIR_REC_LEN(de) >=
4958             __LDISKFS_DIR_REC_LEN(dot_dotdot + 1 + sizeof(struct osd_fid_pack)))
4959                 return 1;
4960         else
4961                 return 0;
4962 }
4963
4964 static int
4965 osd_dirent_reinsert(const struct lu_env *env, handle_t *jh,
4966                     struct inode *dir, struct inode *inode,
4967                     struct osd_it_ea_dirent *ent, struct lu_fid *fid,
4968                     struct buffer_head *bh, struct ldiskfs_dir_entry_2 *de,
4969                     struct htree_lock *hlock)
4970 {
4971         struct dentry               *dentry;
4972         struct osd_fid_pack         *rec;
4973         struct ldiskfs_dentry_param *ldp;
4974         int                          rc;
4975         ENTRY;
4976
4977         if (!LDISKFS_HAS_INCOMPAT_FEATURE(inode->i_sb,
4978                                           LDISKFS_FEATURE_INCOMPAT_DIRDATA))
4979                 RETURN(0);
4980
4981         /* There is enough space to hold the FID-in-dirent. */
4982         if (osd_dirent_has_space(de->rec_len, ent->oied_namelen,
4983                                  dir->i_sb->s_blocksize)) {
4984                 rc = ldiskfs_journal_get_write_access(jh, bh);
4985                 if (rc != 0) {
4986                         CERROR("%.16s: fail to write access for reinsert "
4987                                "dirent: name = %.*s, rc = %d\n",
4988                                LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4989                                ent->oied_namelen, ent->oied_name, rc);
4990                         RETURN(rc);
4991                 }
4992
4993                 de->name[de->name_len] = 0;
4994                 rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
4995                 rec->fp_len = sizeof(struct lu_fid) + 1;
4996                 fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
4997                 de->file_type |= LDISKFS_DIRENT_LUFID;
4998
4999                 rc = ldiskfs_journal_dirty_metadata(jh, bh);
5000                 if (rc != 0)
5001                         CERROR("%.16s: fail to dirty metadata for reinsert "
5002                                "dirent: name = %.*s, rc = %d\n",
5003                                LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
5004                                ent->oied_namelen, ent->oied_name, rc);
5005
5006                 RETURN(rc);
5007         }
5008
5009         rc = ldiskfs_delete_entry(jh, dir, de, bh);
5010         if (rc != 0) {
5011                 CERROR("%.16s: fail to delete entry for reinsert dirent: "
5012                        "name = %.*s, rc = %d\n",
5013                        LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
5014                        ent->oied_namelen, ent->oied_name, rc);
5015                 RETURN(rc);
5016         }
5017
5018         dentry = osd_child_dentry_by_inode(env, dir, ent->oied_name,
5019                                            ent->oied_namelen);
5020         ldp = (struct ldiskfs_dentry_param *)osd_oti_get(env)->oti_ldp;
5021         osd_get_ldiskfs_dirent_param(ldp, (const struct dt_rec *)fid);
5022         dentry->d_fsdata = (void *)ldp;
5023         ll_vfs_dq_init(dir);
5024         rc = osd_ldiskfs_add_entry(jh, dentry, inode, hlock);
5025         /* It is too bad, we cannot reinsert the name entry back.
5026          * That means we lose it! */
5027         if (rc != 0)
5028                 CERROR("%.16s: fail to insert entry for reinsert dirent: "
5029                        "name = %.*s, rc = %d\n",
5030                        LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
5031                        ent->oied_namelen, ent->oied_name, rc);
5032
5033         RETURN(rc);
5034 }
5035
5036 static int
5037 osd_dirent_check_repair(const struct lu_env *env, struct osd_object *obj,
5038                         struct osd_it_ea *it, struct lu_fid *fid,
5039                         struct osd_inode_id *id, __u32 *attr)
5040 {
5041         struct osd_thread_info     *info        = osd_oti_get(env);
5042         struct lustre_mdt_attrs    *lma         = &info->oti_mdt_attrs;
5043         struct osd_device          *dev         = osd_obj2dev(obj);
5044         struct super_block         *sb          = osd_sb(dev);
5045         const char                 *devname     =
5046                                         LDISKFS_SB(sb)->s_es->s_volume_name;
5047         struct osd_it_ea_dirent    *ent         = it->oie_dirent;
5048         struct inode               *dir         = obj->oo_inode;
5049         struct htree_lock          *hlock       = NULL;
5050         struct buffer_head         *bh          = NULL;
5051         handle_t                   *jh          = NULL;
5052         struct ldiskfs_dir_entry_2 *de;
5053         struct dentry              *dentry;
5054         struct inode               *inode;
5055         int                         credits;
5056         int                         rc;
5057         int                         dot_dotdot  = 0;
5058         bool                        dirty       = false;
5059         ENTRY;
5060
5061         if (ent->oied_name[0] == '.') {
5062                 if (ent->oied_namelen == 1)
5063                         dot_dotdot = 1;
5064                 else if (ent->oied_namelen == 2 && ent->oied_name[1] == '.')
5065                         dot_dotdot = 2;
5066         }
5067
5068         dentry = osd_child_dentry_get(env, obj, ent->oied_name,
5069                                       ent->oied_namelen);
5070
5071         /* We need to ensure that the name entry is still valid.
5072          * Because it may be removed or renamed by other already.
5073          *
5074          * The unlink or rename operation will start journal before PDO lock,
5075          * so to avoid deadlock, here we need to start journal handle before
5076          * related PDO lock also. But because we do not know whether there
5077          * will be something to be repaired before PDO lock, we just start
5078          * journal without conditions.
5079          *
5080          * We may need to remove the name entry firstly, then insert back.
5081          * One credit is for user quota file update.
5082          * One credit is for group quota file update.
5083          * Two credits are for dirty inode. */
5084         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE] +
5085                   osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1 + 1 + 2;
5086
5087 again:
5088         if (dev->od_dirent_journal) {
5089                 jh = osd_journal_start_sb(sb, LDISKFS_HT_MISC, credits);
5090                 if (IS_ERR(jh)) {
5091                         rc = PTR_ERR(jh);
5092                         CERROR("%.16s: fail to start trans for dirent "
5093                                "check_repair: credits %d, name %.*s, rc %d\n",
5094                                devname, credits, ent->oied_namelen,
5095                                ent->oied_name, rc);
5096                         RETURN(rc);
5097                 }
5098
5099                 if (obj->oo_hl_head != NULL) {
5100                         hlock = osd_oti_get(env)->oti_hlock;
5101                         /* "0" means exclusive lock for the whole directory.
5102                          * We need to prevent others access such name entry
5103                          * during the delete + insert. Neither HLOCK_ADD nor
5104                          * HLOCK_DEL cannot guarantee the atomicity. */
5105                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir, 0);
5106                 } else {
5107                         down_write(&obj->oo_ext_idx_sem);
5108                 }
5109         } else {
5110                 if (obj->oo_hl_head != NULL) {
5111                         hlock = osd_oti_get(env)->oti_hlock;
5112                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir,
5113                                            LDISKFS_HLOCK_LOOKUP);
5114                 } else {
5115                         down_read(&obj->oo_ext_idx_sem);
5116                 }
5117         }
5118
5119         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
5120         /* For dot/dotdot entry, if there is not enough space to hold the
5121          * FID-in-dirent, just keep them there. It only happens when the
5122          * device upgraded from 1.8 or restored from MDT file-level backup.
5123          * For the whole directory, only dot/dotdot entry have no FID-in-dirent
5124          * and needs to get FID from LMA when readdir, it will not affect the
5125          * performance much. */
5126         if ((bh == NULL) || (le32_to_cpu(de->inode) != ent->oied_ino) ||
5127             (dot_dotdot != 0 && !osd_dot_dotdot_has_space(de, dot_dotdot))) {
5128                 *attr |= LUDA_IGNORE;
5129                 GOTO(out_journal, rc = 0);
5130         }
5131
5132         osd_id_gen(id, ent->oied_ino, OSD_OII_NOGEN);
5133         inode = osd_iget(info, dev, id);
5134         if (IS_ERR(inode)) {
5135                 rc = PTR_ERR(inode);
5136                 if (rc == -ENOENT || rc == -ESTALE) {
5137                         *attr |= LUDA_IGNORE;
5138                         rc = 0;
5139                 }
5140
5141                 GOTO(out_journal, rc);
5142         }
5143
5144         /* skip the REMOTE_PARENT_DIR. */
5145         if (inode == dev->od_mdt_map->omm_remote_parent->d_inode)
5146                 GOTO(out_inode, rc = 0);
5147
5148         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
5149         if (rc == 0) {
5150                 LASSERT(!(lma->lma_compat & LMAC_NOT_IN_OI));
5151
5152                 if (fid_is_sane(fid)) {
5153                         /* FID-in-dirent is valid. */
5154                         if (lu_fid_eq(fid, &lma->lma_self_fid))
5155                                 GOTO(out_inode, rc = 0);
5156
5157                         /* Do not repair under dryrun mode. */
5158                         if (*attr & LUDA_VERIFY_DRYRUN) {
5159                                 *attr |= LUDA_REPAIR;
5160                                 GOTO(out_inode, rc = 0);
5161                         }
5162
5163                         if (!dev->od_dirent_journal) {
5164                                 iput(inode);
5165                                 brelse(bh);
5166                                 if (hlock != NULL)
5167                                         ldiskfs_htree_unlock(hlock);
5168                                 else
5169                                         up_read(&obj->oo_ext_idx_sem);
5170                                 dev->od_dirent_journal = 1;
5171                                 goto again;
5172                         }
5173
5174                         *fid = lma->lma_self_fid;
5175                         dirty = true;
5176                         /* Update the FID-in-dirent. */
5177                         rc = osd_dirent_update(jh, sb, ent, fid, bh, de);
5178                         if (rc == 0)
5179                                 *attr |= LUDA_REPAIR;
5180                 } else {
5181                         /* Do not repair under dryrun mode. */
5182                         if (*attr & LUDA_VERIFY_DRYRUN) {
5183                                 *fid = lma->lma_self_fid;
5184                                 *attr |= LUDA_REPAIR;
5185                                 GOTO(out_inode, rc = 0);
5186                         }
5187
5188                         if (!dev->od_dirent_journal) {
5189                                 iput(inode);
5190                                 brelse(bh);
5191                                 if (hlock != NULL)
5192                                         ldiskfs_htree_unlock(hlock);
5193                                 else
5194                                         up_read(&obj->oo_ext_idx_sem);
5195                                 dev->od_dirent_journal = 1;
5196                                 goto again;
5197                         }
5198
5199                         *fid = lma->lma_self_fid;
5200                         dirty = true;
5201                         /* Append the FID-in-dirent. */
5202                         rc = osd_dirent_reinsert(env, jh, dir, inode, ent,
5203                                                  fid, bh, de, hlock);
5204                         if (rc == 0)
5205                                 *attr |= LUDA_REPAIR;
5206                 }
5207         } else if (rc == -ENODATA) {
5208                 /* Do not repair under dryrun mode. */
5209                 if (*attr & LUDA_VERIFY_DRYRUN) {
5210                         if (fid_is_sane(fid)) {
5211                                 *attr |= LUDA_REPAIR;
5212                         } else {
5213                                 lu_igif_build(fid, inode->i_ino,
5214                                               inode->i_generation);
5215                                 *attr |= LUDA_UPGRADE;
5216                         }
5217                         GOTO(out_inode, rc = 0);
5218                 }
5219
5220                 if (!dev->od_dirent_journal) {
5221                         iput(inode);
5222                         brelse(bh);
5223                         if (hlock != NULL)
5224                                 ldiskfs_htree_unlock(hlock);
5225                         else
5226                                 up_read(&obj->oo_ext_idx_sem);
5227                         dev->od_dirent_journal = 1;
5228                         goto again;
5229                 }
5230
5231                 dirty = true;
5232                 if (unlikely(fid_is_sane(fid))) {
5233                         /* FID-in-dirent exists, but FID-in-LMA is lost.
5234                          * Trust the FID-in-dirent, and add FID-in-LMA. */
5235                         rc = osd_ea_fid_set(info, inode, fid, 0, 0);
5236                         if (rc == 0)
5237                                 *attr |= LUDA_REPAIR;
5238                 } else {
5239                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
5240                         /* It is probably IGIF object. Only aappend the
5241                          * FID-in-dirent. OI scrub will process FID-in-LMA. */
5242                         rc = osd_dirent_reinsert(env, jh, dir, inode, ent,
5243                                                  fid, bh, de, hlock);
5244                         if (rc == 0)
5245                                 *attr |= LUDA_UPGRADE;
5246                 }
5247         }
5248
5249         GOTO(out_inode, rc);
5250
5251 out_inode:
5252         iput(inode);
5253
5254 out_journal:
5255         brelse(bh);
5256         if (hlock != NULL) {
5257                 ldiskfs_htree_unlock(hlock);
5258         } else {
5259                 if (dev->od_dirent_journal)
5260                         up_write(&obj->oo_ext_idx_sem);
5261                 else
5262                         up_read(&obj->oo_ext_idx_sem);
5263         }
5264         if (jh != NULL)
5265                 ldiskfs_journal_stop(jh);
5266         if (rc >= 0 && !dirty)
5267                 dev->od_dirent_journal = 0;
5268         return rc;
5269 }
5270
5271 /**
5272  * Returns the value at current position from iterator's in memory structure.
5273  *
5274  * \param di struct osd_it_ea, iterator's in memory structure
5275  * \param attr attr requested for dirent.
5276  * \param lde lustre dirent
5277  *
5278  * \retval   0 no error and \param lde has correct lustre dirent.
5279  * \retval -ve on error
5280  */
5281 static inline int osd_it_ea_rec(const struct lu_env *env,
5282                                 const struct dt_it *di,
5283                                 struct dt_rec *dtrec, __u32 attr)
5284 {
5285         struct osd_it_ea       *it    = (struct osd_it_ea *)di;
5286         struct osd_object      *obj   = it->oie_obj;
5287         struct osd_device      *dev   = osd_obj2dev(obj);
5288         struct osd_scrub       *scrub = &dev->od_scrub;
5289         struct scrub_file      *sf    = &scrub->os_file;
5290         struct osd_thread_info *oti   = osd_oti_get(env);
5291         struct osd_inode_id    *id    = &oti->oti_id;
5292         struct osd_idmap_cache *oic   = &oti->oti_cache;
5293         struct lu_fid          *fid   = &it->oie_dirent->oied_fid;
5294         struct lu_dirent       *lde   = (struct lu_dirent *)dtrec;
5295         __u32                   ino   = it->oie_dirent->oied_ino;
5296         int                     rc    = 0;
5297         ENTRY;
5298
5299         if (attr & LUDA_VERIFY) {
5300                 attr |= LUDA_TYPE;
5301                 if (unlikely(ino == osd_sb(dev)->s_root->d_inode->i_ino)) {
5302                         attr |= LUDA_IGNORE;
5303                         rc = 0;
5304                 } else {
5305                         rc = osd_dirent_check_repair(env, obj, it, fid, id,
5306                                                      &attr);
5307                 }
5308         } else {
5309                 attr &= ~LU_DIRENT_ATTRS_MASK;
5310                 if (!fid_is_sane(fid)) {
5311                         if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP))
5312                                 RETURN(-ENOENT);
5313
5314                         rc = osd_ea_fid_get(env, obj, ino, fid, id);
5315                 } else {
5316                         osd_id_gen(id, ino, OSD_OII_NOGEN);
5317                 }
5318         }
5319
5320         /* Pack the entry anyway, at least the offset is right. */
5321         osd_it_pack_dirent(lde, fid, it->oie_dirent->oied_off,
5322                            it->oie_dirent->oied_name,
5323                            it->oie_dirent->oied_namelen,
5324                            it->oie_dirent->oied_type, attr);
5325
5326         if (rc < 0)
5327                 RETURN(rc);
5328
5329         if (osd_remote_fid(env, dev, fid))
5330                 RETURN(0);
5331
5332         if (likely(!(attr & LUDA_IGNORE)))
5333                 rc = osd_add_oi_cache(oti, dev, id, fid);
5334
5335         if (!(attr & LUDA_VERIFY) &&
5336             (scrub->os_pos_current <= ino) &&
5337             ((sf->sf_flags & SF_INCONSISTENT) ||
5338              (sf->sf_flags & SF_UPGRADE && fid_is_igif(fid)) ||
5339              ldiskfs_test_bit(osd_oi_fid2idx(dev, fid), sf->sf_oi_bitmap)))
5340                 osd_consistency_check(oti, dev, oic);
5341
5342         RETURN(rc);
5343 }
5344
5345 /**
5346  * Returns a cookie for current position of the iterator head, so that
5347  * user can use this cookie to load/start the iterator next time.
5348  *
5349  * \param di iterator's in memory structure
5350  *
5351  * \retval cookie for current position, on success
5352  */
5353 static __u64 osd_it_ea_store(const struct lu_env *env, const struct dt_it *di)
5354 {
5355         struct osd_it_ea *it = (struct osd_it_ea *)di;
5356
5357         return it->oie_dirent->oied_off;
5358 }
5359
5360 /**
5361  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
5362  * to load a directory entry at a time and stored it i inn,
5363  * in iterator's in-memory data structure.
5364  *
5365  * \param di struct osd_it_ea, iterator's in memory structure
5366  *
5367  * \retval +ve on success
5368  * \retval -ve on error
5369  */
5370 static int osd_it_ea_load(const struct lu_env *env,
5371                           const struct dt_it *di, __u64 hash)
5372 {
5373         struct osd_it_ea *it = (struct osd_it_ea *)di;
5374         int rc;
5375
5376         ENTRY;
5377         it->oie_file.f_pos = hash;
5378
5379         rc =  osd_ldiskfs_it_fill(env, di);
5380         if (rc == 0)
5381                 rc = +1;
5382
5383         RETURN(rc);
5384 }
5385
5386 /**
5387  * Index lookup function for interoperability mode (b11826).
5388  *
5389  * \param key,  key i.e. file name to be searched
5390  *
5391  * \retval +ve, on success
5392  * \retval -ve, on error
5393  */
5394 static int osd_index_ea_lookup(const struct lu_env *env, struct dt_object *dt,
5395                                struct dt_rec *rec, const struct dt_key *key,
5396                                struct lustre_capa *capa)
5397 {
5398         struct osd_object *obj = osd_dt_obj(dt);
5399         int rc = 0;
5400
5401         ENTRY;
5402
5403         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
5404         LINVRNT(osd_invariant(obj));
5405
5406         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
5407                 return -EACCES;
5408
5409         rc = osd_ea_lookup_rec(env, obj, rec, key);
5410         if (rc == 0)
5411                 rc = +1;
5412         RETURN(rc);
5413 }
5414
5415 /**
5416  * Index and Iterator operations for interoperability
5417  * mode (i.e. to run 2.0 mds on 1.8 disk) (b11826)
5418  */
5419 static const struct dt_index_operations osd_index_ea_ops = {
5420         .dio_lookup         = osd_index_ea_lookup,
5421         .dio_declare_insert = osd_index_declare_ea_insert,
5422         .dio_insert         = osd_index_ea_insert,
5423         .dio_declare_delete = osd_index_declare_ea_delete,
5424         .dio_delete         = osd_index_ea_delete,
5425         .dio_it     = {
5426                 .init     = osd_it_ea_init,
5427                 .fini     = osd_it_ea_fini,
5428                 .get      = osd_it_ea_get,
5429                 .put      = osd_it_ea_put,
5430                 .next     = osd_it_ea_next,
5431                 .key      = osd_it_ea_key,
5432                 .key_size = osd_it_ea_key_size,
5433                 .rec      = osd_it_ea_rec,
5434                 .store    = osd_it_ea_store,
5435                 .load     = osd_it_ea_load
5436         }
5437 };
5438
5439 static void *osd_key_init(const struct lu_context *ctx,
5440                           struct lu_context_key *key)
5441 {
5442         struct osd_thread_info *info;
5443
5444         OBD_ALLOC_PTR(info);
5445         if (info == NULL)
5446                 return ERR_PTR(-ENOMEM);
5447
5448         OBD_ALLOC(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5449         if (info->oti_it_ea_buf == NULL)
5450                 goto out_free_info;
5451
5452         info->oti_env = container_of(ctx, struct lu_env, le_ctx);
5453
5454         info->oti_hlock = ldiskfs_htree_lock_alloc();
5455         if (info->oti_hlock == NULL)
5456                 goto out_free_ea;
5457
5458         return info;
5459
5460  out_free_ea:
5461         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5462  out_free_info:
5463         OBD_FREE_PTR(info);
5464         return ERR_PTR(-ENOMEM);
5465 }
5466
5467 static void osd_key_fini(const struct lu_context *ctx,
5468                          struct lu_context_key *key, void* data)
5469 {
5470         struct osd_thread_info *info = data;
5471
5472         if (info->oti_hlock != NULL)
5473                 ldiskfs_htree_lock_free(info->oti_hlock);
5474         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5475         lu_buf_free(&info->oti_iobuf.dr_pg_buf);
5476         lu_buf_free(&info->oti_iobuf.dr_bl_buf);
5477         OBD_FREE_PTR(info);
5478 }
5479
5480 static void osd_key_exit(const struct lu_context *ctx,
5481                          struct lu_context_key *key, void *data)
5482 {
5483         struct osd_thread_info *info = data;
5484
5485         LASSERT(info->oti_r_locks == 0);
5486         LASSERT(info->oti_w_locks == 0);
5487         LASSERT(info->oti_txns    == 0);
5488 }
5489
5490 /* type constructor/destructor: osd_type_init, osd_type_fini */
5491 LU_TYPE_INIT_FINI(osd, &osd_key);
5492
5493 struct lu_context_key osd_key = {
5494         .lct_tags = LCT_DT_THREAD | LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL,
5495         .lct_init = osd_key_init,
5496         .lct_fini = osd_key_fini,
5497         .lct_exit = osd_key_exit
5498 };
5499
5500
5501 static int osd_device_init(const struct lu_env *env, struct lu_device *d,
5502                            const char *name, struct lu_device *next)
5503 {
5504         struct osd_device *osd = osd_dev(d);
5505
5506         if (strlcpy(osd->od_svname, name, sizeof(osd->od_svname))
5507             >= sizeof(osd->od_svname))
5508                 return -E2BIG;
5509         return osd_procfs_init(osd, name);
5510 }
5511
5512 static int osd_shutdown(const struct lu_env *env, struct osd_device *o)
5513 {
5514         ENTRY;
5515
5516         /* shutdown quota slave instance associated with the device */
5517         if (o->od_quota_slave != NULL) {
5518                 qsd_fini(env, o->od_quota_slave);
5519                 o->od_quota_slave = NULL;
5520         }
5521
5522         RETURN(0);
5523 }
5524
5525 static void osd_umount(const struct lu_env *env, struct osd_device *o)
5526 {
5527         ENTRY;
5528
5529         if (o->od_mnt != NULL) {
5530                 shrink_dcache_sb(osd_sb(o));
5531                 osd_sync(env, &o->od_dt_dev);
5532
5533                 mntput(o->od_mnt);
5534                 o->od_mnt = NULL;
5535         }
5536
5537         EXIT;
5538 }
5539
5540 static int osd_mount(const struct lu_env *env,
5541                      struct osd_device *o, struct lustre_cfg *cfg)
5542 {
5543         const char              *name  = lustre_cfg_string(cfg, 0);
5544         const char              *dev  = lustre_cfg_string(cfg, 1);
5545         const char              *opts;
5546         unsigned long            page, s_flags, lmd_flags = 0;
5547         struct page             *__page;
5548         struct file_system_type *type;
5549         char                    *options = NULL;
5550         char                    *str;
5551         struct osd_thread_info  *info = osd_oti_get(env);
5552         struct lu_fid           *fid = &info->oti_fid;
5553         struct inode            *inode;
5554         int                      rc = 0;
5555         ENTRY;
5556
5557         if (o->od_mnt != NULL)
5558                 RETURN(0);
5559
5560         if (strlen(dev) >= sizeof(o->od_mntdev))
5561                 RETURN(-E2BIG);
5562         strcpy(o->od_mntdev, dev);
5563
5564         OBD_PAGE_ALLOC(__page, GFP_IOFS);
5565         if (__page == NULL)
5566                 GOTO(out, rc = -ENOMEM);
5567
5568         str = lustre_cfg_string(cfg, 2);
5569         s_flags = simple_strtoul(str, NULL, 0);
5570         str = strstr(str, ":");
5571         if (str)
5572                 lmd_flags = simple_strtoul(str + 1, NULL, 0);
5573         opts = lustre_cfg_string(cfg, 3);
5574         page = (unsigned long)page_address(__page);
5575         options = (char *)page;
5576         *options = '\0';
5577         if (opts == NULL)
5578                 strcat(options, "user_xattr,acl");
5579         else
5580                 strcat(options, opts);
5581
5582         /* Glom up mount options */
5583         if (*options != '\0')
5584                 strcat(options, ",");
5585         strlcat(options, "no_mbcache", PAGE_CACHE_SIZE);
5586
5587         type = get_fs_type("ldiskfs");
5588         if (!type) {
5589                 CERROR("%s: cannot find ldiskfs module\n", name);
5590                 GOTO(out, rc = -ENODEV);
5591         }
5592
5593         o->od_mnt = vfs_kern_mount(type, s_flags, dev, options);
5594         module_put(type->owner);
5595
5596         if (IS_ERR(o->od_mnt)) {
5597                 rc = PTR_ERR(o->od_mnt);
5598                 o->od_mnt = NULL;
5599                 CERROR("%s: can't mount %s: %d\n", name, dev, rc);
5600                 GOTO(out, rc);
5601         }
5602
5603 #ifdef HAVE_DEV_SET_RDONLY
5604         if (dev_check_rdonly(o->od_mnt->mnt_sb->s_bdev)) {
5605                 CERROR("%s: underlying device %s is marked as read-only. "
5606                        "Setup failed\n", name, dev);
5607                 GOTO(out_mnt, rc = -EROFS);
5608         }
5609 #endif
5610
5611         if (!LDISKFS_HAS_COMPAT_FEATURE(o->od_mnt->mnt_sb,
5612                                         LDISKFS_FEATURE_COMPAT_HAS_JOURNAL)) {
5613                 CERROR("%s: device %s is mounted w/o journal\n", name, dev);
5614                 GOTO(out_mnt, rc = -EINVAL);
5615         }
5616
5617 #ifdef LDISKFS_MOUNT_DIRDATA
5618         if (LDISKFS_HAS_INCOMPAT_FEATURE(o->od_mnt->mnt_sb,
5619                                          LDISKFS_FEATURE_INCOMPAT_DIRDATA))
5620                 LDISKFS_SB(osd_sb(o))->s_mount_opt |= LDISKFS_MOUNT_DIRDATA;
5621 #endif
5622         inode = osd_sb(o)->s_root->d_inode;
5623         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
5624         rc = osd_ea_fid_set(info, inode, fid, LMAC_NOT_IN_OI, 0);
5625         if (rc != 0) {
5626                 CERROR("%s: failed to set lma on %s root inode\n", name, dev);
5627                 GOTO(out_mnt, rc);
5628         }
5629
5630         if (lmd_flags & LMD_FLG_NOSCRUB)
5631                 o->od_noscrub = 1;
5632
5633         GOTO(out, rc = 0);
5634
5635 out_mnt:
5636         mntput(o->od_mnt);
5637         o->od_mnt = NULL;
5638
5639 out:
5640         if (__page)
5641                 OBD_PAGE_FREE(__page);
5642
5643         return rc;
5644 }
5645
5646 static struct lu_device *osd_device_fini(const struct lu_env *env,
5647                                          struct lu_device *d)
5648 {
5649         struct osd_device *o = osd_dev(d);
5650         ENTRY;
5651
5652         osd_shutdown(env, o);
5653         osd_procfs_fini(o);
5654         osd_scrub_cleanup(env, o);
5655         osd_obj_map_fini(o);
5656         osd_umount(env, o);
5657
5658         RETURN(NULL);
5659 }
5660
5661 static int osd_device_init0(const struct lu_env *env,
5662                             struct osd_device *o,
5663                             struct lustre_cfg *cfg)
5664 {
5665         struct lu_device        *l = osd2lu_dev(o);
5666         struct osd_thread_info *info;
5667         int                     rc;
5668         int                     cplen = 0;
5669
5670         /* if the module was re-loaded, env can loose its keys */
5671         rc = lu_env_refill((struct lu_env *) env);
5672         if (rc)
5673                 GOTO(out, rc);
5674         info = osd_oti_get(env);
5675         LASSERT(info);
5676
5677         l->ld_ops = &osd_lu_ops;
5678         o->od_dt_dev.dd_ops = &osd_dt_ops;
5679
5680         spin_lock_init(&o->od_osfs_lock);
5681         mutex_init(&o->od_otable_mutex);
5682         o->od_osfs_age = cfs_time_shift_64(-1000);
5683
5684         o->od_capa_hash = init_capa_hash();
5685         if (o->od_capa_hash == NULL)
5686                 GOTO(out, rc = -ENOMEM);
5687
5688         o->od_read_cache = 1;
5689         o->od_writethrough_cache = 1;
5690         o->od_readcache_max_filesize = OSD_MAX_CACHE_SIZE;
5691
5692         rc = osd_mount(env, o, cfg);
5693         if (rc)
5694                 GOTO(out_capa, rc);
5695
5696         cplen = strlcpy(o->od_svname, lustre_cfg_string(cfg, 4),
5697                         sizeof(o->od_svname));
5698         if (cplen >= sizeof(o->od_svname)) {
5699                 rc = -E2BIG;
5700                 GOTO(out_mnt, rc);
5701         }
5702
5703         if (server_name_is_ost(o->od_svname))
5704                 o->od_is_ost = 1;
5705
5706         rc = osd_obj_map_init(env, o);
5707         if (rc != 0)
5708                 GOTO(out_mnt, rc);
5709
5710         rc = lu_site_init(&o->od_site, l);
5711         if (rc != 0)
5712                 GOTO(out_compat, rc);
5713         o->od_site.ls_bottom_dev = l;
5714
5715         rc = lu_site_init_finish(&o->od_site);
5716         if (rc != 0)
5717                 GOTO(out_site, rc);
5718
5719         /* self-repair LMA by default */
5720         o->od_lma_self_repair = 1;
5721
5722         CFS_INIT_LIST_HEAD(&o->od_ios_list);
5723         /* setup scrub, including OI files initialization */
5724         rc = osd_scrub_setup(env, o);
5725         if (rc < 0)
5726                 GOTO(out_site, rc);
5727
5728         rc = osd_procfs_init(o, o->od_svname);
5729         if (rc != 0) {
5730                 CERROR("%s: can't initialize procfs: rc = %d\n",
5731                        o->od_svname, rc);
5732                 GOTO(out_scrub, rc);
5733         }
5734
5735         LASSERT(l->ld_site->ls_linkage.next && l->ld_site->ls_linkage.prev);
5736
5737         /* initialize quota slave instance */
5738         o->od_quota_slave = qsd_init(env, o->od_svname, &o->od_dt_dev,
5739                                      o->od_proc_entry);
5740         if (IS_ERR(o->od_quota_slave)) {
5741                 rc = PTR_ERR(o->od_quota_slave);
5742                 o->od_quota_slave = NULL;
5743                 GOTO(out_procfs, rc);
5744         }
5745
5746         RETURN(0);
5747
5748 out_procfs:
5749         osd_procfs_fini(o);
5750 out_scrub:
5751         osd_scrub_cleanup(env, o);
5752 out_site:
5753         lu_site_fini(&o->od_site);
5754 out_compat:
5755         osd_obj_map_fini(o);
5756 out_mnt:
5757         osd_umount(env, o);
5758 out_capa:
5759         cleanup_capa_hash(o->od_capa_hash);
5760 out:
5761         return rc;
5762 }
5763
5764 static struct lu_device *osd_device_alloc(const struct lu_env *env,
5765                                           struct lu_device_type *t,
5766                                           struct lustre_cfg *cfg)
5767 {
5768         struct osd_device *o;
5769         int                rc;
5770
5771         OBD_ALLOC_PTR(o);
5772         if (o == NULL)
5773                 return ERR_PTR(-ENOMEM);
5774
5775         rc = dt_device_init(&o->od_dt_dev, t);
5776         if (rc == 0) {
5777                 /* Because the ctx might be revived in dt_device_init,
5778                  * refill the env here */
5779                 lu_env_refill((struct lu_env *)env);
5780                 rc = osd_device_init0(env, o, cfg);
5781                 if (rc)
5782                         dt_device_fini(&o->od_dt_dev);
5783         }
5784
5785         if (unlikely(rc != 0))
5786                 OBD_FREE_PTR(o);
5787
5788         return rc == 0 ? osd2lu_dev(o) : ERR_PTR(rc);
5789 }
5790
5791 static struct lu_device *osd_device_free(const struct lu_env *env,
5792                                          struct lu_device *d)
5793 {
5794         struct osd_device *o = osd_dev(d);
5795         ENTRY;
5796
5797         cleanup_capa_hash(o->od_capa_hash);
5798         /* XXX: make osd top device in order to release reference */
5799         d->ld_site->ls_top_dev = d;
5800         lu_site_purge(env, d->ld_site, -1);
5801         if (!cfs_hash_is_empty(d->ld_site->ls_obj_hash)) {
5802                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, D_ERROR, NULL);
5803                 lu_site_print(env, d->ld_site, &msgdata, lu_cdebug_printer);
5804         }
5805         lu_site_fini(&o->od_site);
5806         dt_device_fini(&o->od_dt_dev);
5807         OBD_FREE_PTR(o);
5808         RETURN(NULL);
5809 }
5810
5811 static int osd_process_config(const struct lu_env *env,
5812                               struct lu_device *d, struct lustre_cfg *cfg)
5813 {
5814         struct osd_device               *o = osd_dev(d);
5815         int                             rc;
5816         ENTRY;
5817
5818         switch (cfg->lcfg_command) {
5819         case LCFG_SETUP:
5820                 rc = osd_mount(env, o, cfg);
5821                 break;
5822         case LCFG_CLEANUP:
5823                 lu_dev_del_linkage(d->ld_site, d);
5824                 rc = osd_shutdown(env, o);
5825                 break;
5826         case LCFG_PARAM:
5827                 LASSERT(&o->od_dt_dev);
5828                 rc = class_process_proc_param(PARAM_OSD, lprocfs_osd_obd_vars,
5829                                               cfg, &o->od_dt_dev);
5830                 if (rc > 0 || rc == -ENOSYS)
5831                         rc = class_process_proc_param(PARAM_OST,
5832                                                       lprocfs_osd_obd_vars,
5833                                                       cfg, &o->od_dt_dev);
5834                 break;
5835         default:
5836                 rc = -ENOSYS;
5837         }
5838
5839         RETURN(rc);
5840 }
5841
5842 static int osd_recovery_complete(const struct lu_env *env,
5843                                  struct lu_device *d)
5844 {
5845         struct osd_device       *osd = osd_dev(d);
5846         int                      rc = 0;
5847         ENTRY;
5848
5849         if (osd->od_quota_slave == NULL)
5850                 RETURN(0);
5851
5852         /* start qsd instance on recovery completion, this notifies the quota
5853          * slave code that we are about to process new requests now */
5854         rc = qsd_start(env, osd->od_quota_slave);
5855         RETURN(rc);
5856 }
5857
5858 /*
5859  * we use exports to track all osd users
5860  */
5861 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
5862                            struct obd_device *obd, struct obd_uuid *cluuid,
5863                            struct obd_connect_data *data, void *localdata)
5864 {
5865         struct osd_device    *osd = osd_dev(obd->obd_lu_dev);
5866         struct lustre_handle  conn;
5867         int                   rc;
5868         ENTRY;
5869
5870         CDEBUG(D_CONFIG, "connect #%d\n", osd->od_connects);
5871
5872         rc = class_connect(&conn, obd, cluuid);
5873         if (rc)
5874                 RETURN(rc);
5875
5876         *exp = class_conn2export(&conn);
5877
5878         spin_lock(&osd->od_osfs_lock);
5879         osd->od_connects++;
5880         spin_unlock(&osd->od_osfs_lock);
5881
5882         RETURN(0);
5883 }
5884
5885 /*
5886  * once last export (we don't count self-export) disappeared
5887  * osd can be released
5888  */
5889 static int osd_obd_disconnect(struct obd_export *exp)
5890 {
5891         struct obd_device *obd = exp->exp_obd;
5892         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
5893         int                rc, release = 0;
5894         ENTRY;
5895
5896         /* Only disconnect the underlying layers on the final disconnect. */
5897         spin_lock(&osd->od_osfs_lock);
5898         osd->od_connects--;
5899         if (osd->od_connects == 0)
5900                 release = 1;
5901         spin_unlock(&osd->od_osfs_lock);
5902
5903         rc = class_disconnect(exp); /* bz 9811 */
5904
5905         if (rc == 0 && release)
5906                 class_manual_cleanup(obd);
5907         RETURN(rc);
5908 }
5909
5910 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
5911                        struct lu_device *dev)
5912 {
5913         struct osd_device *osd = osd_dev(dev);
5914         int                result = 0;
5915         ENTRY;
5916
5917         if (osd->od_quota_slave != NULL)
5918                 /* set up quota slave objects */
5919                 result = qsd_prepare(env, osd->od_quota_slave);
5920
5921         RETURN(result);
5922 }
5923
5924 static const struct lu_object_operations osd_lu_obj_ops = {
5925         .loo_object_init      = osd_object_init,
5926         .loo_object_delete    = osd_object_delete,
5927         .loo_object_release   = osd_object_release,
5928         .loo_object_free      = osd_object_free,
5929         .loo_object_print     = osd_object_print,
5930         .loo_object_invariant = osd_object_invariant
5931 };
5932
5933 const struct lu_device_operations osd_lu_ops = {
5934         .ldo_object_alloc      = osd_object_alloc,
5935         .ldo_process_config    = osd_process_config,
5936         .ldo_recovery_complete = osd_recovery_complete,
5937         .ldo_prepare           = osd_prepare,
5938 };
5939
5940 static const struct lu_device_type_operations osd_device_type_ops = {
5941         .ldto_init = osd_type_init,
5942         .ldto_fini = osd_type_fini,
5943
5944         .ldto_start = osd_type_start,
5945         .ldto_stop  = osd_type_stop,
5946
5947         .ldto_device_alloc = osd_device_alloc,
5948         .ldto_device_free  = osd_device_free,
5949
5950         .ldto_device_init    = osd_device_init,
5951         .ldto_device_fini    = osd_device_fini
5952 };
5953
5954 struct lu_device_type osd_device_type = {
5955         .ldt_tags     = LU_DEVICE_DT,
5956         .ldt_name     = LUSTRE_OSD_LDISKFS_NAME,
5957         .ldt_ops      = &osd_device_type_ops,
5958         .ldt_ctx_tags = LCT_LOCAL,
5959 };
5960
5961 /*
5962  * lprocfs legacy support.
5963  */
5964 static struct obd_ops osd_obd_device_ops = {
5965         .o_owner = THIS_MODULE,
5966         .o_connect      = osd_obd_connect,
5967         .o_disconnect   = osd_obd_disconnect
5968 };
5969
5970 static int __init osd_mod_init(void)
5971 {
5972         int rc;
5973
5974         osd_oi_mod_init();
5975
5976         rc = lu_kmem_init(ldiskfs_caches);
5977         if (rc)
5978                 return rc;
5979
5980         rc = class_register_type(&osd_obd_device_ops, NULL, NULL,
5981 #ifndef HAVE_ONLY_PROCFS_SEQ
5982                                 lprocfs_osd_module_vars,
5983 #endif
5984                                 LUSTRE_OSD_LDISKFS_NAME, &osd_device_type);
5985         if (rc)
5986                 lu_kmem_fini(ldiskfs_caches);
5987         return rc;
5988 }
5989
5990 static void __exit osd_mod_exit(void)
5991 {
5992         class_unregister_type(LUSTRE_OSD_LDISKFS_NAME);
5993         lu_kmem_fini(ldiskfs_caches);
5994 }
5995
5996 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
5997 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_LDISKFS_NAME")");
5998 MODULE_LICENSE("GPL");
5999
6000 cfs_module(osd, "0.1.0", osd_mod_init, osd_mod_exit);