Whamcloud - gitweb
2288b642741682f8883aa3aaf9d5e56d803becd2
[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 three 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                 ldiskfs_clear_inode_state(inode, LDISKFS_STATE_LUSTRE_NO_OI);
2035                 obj->oo_inode = inode;
2036                 result = 0;
2037         } else {
2038                 if (obj->oo_hl_head != NULL) {
2039                         ldiskfs_htree_lock_head_free(obj->oo_hl_head);
2040                         obj->oo_hl_head = NULL;
2041                 }
2042                 result = PTR_ERR(inode);
2043         }
2044         LINVRNT(osd_invariant(obj));
2045         return result;
2046 }
2047
2048 enum {
2049         OSD_NAME_LEN = 255
2050 };
2051
2052 static int osd_mkdir(struct osd_thread_info *info, struct osd_object *obj,
2053                      struct lu_attr *attr,
2054                      struct dt_allocation_hint *hint,
2055                      struct dt_object_format *dof,
2056                      struct thandle *th)
2057 {
2058         int result;
2059         struct osd_thandle *oth;
2060         __u32 mode = (attr->la_mode & (S_IFMT | S_IRWXUGO | S_ISVTX));
2061
2062         LASSERT(S_ISDIR(attr->la_mode));
2063
2064         oth = container_of(th, struct osd_thandle, ot_super);
2065         LASSERT(oth->ot_handle->h_transaction != NULL);
2066         result = osd_mkfile(info, obj, mode, hint, th);
2067
2068         return result;
2069 }
2070
2071 static int osd_mk_index(struct osd_thread_info *info, struct osd_object *obj,
2072                         struct lu_attr *attr,
2073                         struct dt_allocation_hint *hint,
2074                         struct dt_object_format *dof,
2075                         struct thandle *th)
2076 {
2077         int result;
2078         struct osd_thandle *oth;
2079         const struct dt_index_features *feat = dof->u.dof_idx.di_feat;
2080
2081         __u32 mode = (attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX));
2082
2083         LASSERT(S_ISREG(attr->la_mode));
2084
2085         oth = container_of(th, struct osd_thandle, ot_super);
2086         LASSERT(oth->ot_handle->h_transaction != NULL);
2087
2088         result = osd_mkfile(info, obj, mode, hint, th);
2089         if (result == 0) {
2090                 LASSERT(obj->oo_inode != NULL);
2091                 if (feat->dif_flags & DT_IND_VARKEY)
2092                         result = iam_lvar_create(obj->oo_inode,
2093                                                  feat->dif_keysize_max,
2094                                                  feat->dif_ptrsize,
2095                                                  feat->dif_recsize_max,
2096                                                  oth->ot_handle);
2097                 else
2098                         result = iam_lfix_create(obj->oo_inode,
2099                                                  feat->dif_keysize_max,
2100                                                  feat->dif_ptrsize,
2101                                                  feat->dif_recsize_max,
2102                                                  oth->ot_handle);
2103
2104         }
2105         return result;
2106 }
2107
2108 static int osd_mkreg(struct osd_thread_info *info, struct osd_object *obj,
2109                      struct lu_attr *attr,
2110                      struct dt_allocation_hint *hint,
2111                      struct dt_object_format *dof,
2112                      struct thandle *th)
2113 {
2114         LASSERT(S_ISREG(attr->la_mode));
2115         return osd_mkfile(info, obj, (attr->la_mode &
2116                                (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
2117 }
2118
2119 static int osd_mksym(struct osd_thread_info *info, struct osd_object *obj,
2120                      struct lu_attr *attr,
2121                      struct dt_allocation_hint *hint,
2122                      struct dt_object_format *dof,
2123                      struct thandle *th)
2124 {
2125         LASSERT(S_ISLNK(attr->la_mode));
2126         return osd_mkfile(info, obj, (attr->la_mode &
2127                               (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
2128 }
2129
2130 static int osd_mknod(struct osd_thread_info *info, struct osd_object *obj,
2131                      struct lu_attr *attr,
2132                      struct dt_allocation_hint *hint,
2133                      struct dt_object_format *dof,
2134                      struct thandle *th)
2135 {
2136         umode_t mode = attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX);
2137         int result;
2138
2139         LINVRNT(osd_invariant(obj));
2140         LASSERT(obj->oo_inode == NULL);
2141         LASSERT(S_ISCHR(mode) || S_ISBLK(mode) ||
2142                 S_ISFIFO(mode) || S_ISSOCK(mode));
2143
2144         result = osd_mkfile(info, obj, mode, hint, th);
2145         if (result == 0) {
2146                 LASSERT(obj->oo_inode != NULL);
2147                 /*
2148                  * This inode should be marked dirty for i_rdev.  Currently
2149                  * that is done in the osd_attr_init().
2150                  */
2151                 init_special_inode(obj->oo_inode, obj->oo_inode->i_mode,
2152                                    attr->la_rdev);
2153         }
2154         LINVRNT(osd_invariant(obj));
2155         return result;
2156 }
2157
2158 typedef int (*osd_obj_type_f)(struct osd_thread_info *, struct osd_object *,
2159                               struct lu_attr *,
2160                               struct dt_allocation_hint *hint,
2161                               struct dt_object_format *dof,
2162                               struct thandle *);
2163
2164 static osd_obj_type_f osd_create_type_f(enum dt_format_type type)
2165 {
2166         osd_obj_type_f result;
2167
2168         switch (type) {
2169         case DFT_DIR:
2170                 result = osd_mkdir;
2171                 break;
2172         case DFT_REGULAR:
2173                 result = osd_mkreg;
2174                 break;
2175         case DFT_SYM:
2176                 result = osd_mksym;
2177                 break;
2178         case DFT_NODE:
2179                 result = osd_mknod;
2180                 break;
2181         case DFT_INDEX:
2182                 result = osd_mk_index;
2183                 break;
2184
2185         default:
2186                 LBUG();
2187                 break;
2188         }
2189         return result;
2190 }
2191
2192
2193 static void osd_ah_init(const struct lu_env *env, struct dt_allocation_hint *ah,
2194                         struct dt_object *parent, struct dt_object *child,
2195                         umode_t child_mode)
2196 {
2197         LASSERT(ah);
2198
2199         memset(ah, 0, sizeof(*ah));
2200         ah->dah_parent = parent;
2201         ah->dah_mode = child_mode;
2202 }
2203
2204 static void osd_attr_init(struct osd_thread_info *info, struct osd_object *obj,
2205                           struct lu_attr *attr, struct dt_object_format *dof)
2206 {
2207         struct inode   *inode = obj->oo_inode;
2208         __u64           valid = attr->la_valid;
2209         int             result;
2210
2211         attr->la_valid &= ~(LA_TYPE | LA_MODE);
2212
2213         if (dof->dof_type != DFT_NODE)
2214                 attr->la_valid &= ~LA_RDEV;
2215         if ((valid & LA_ATIME) && (attr->la_atime == LTIME_S(inode->i_atime)))
2216                 attr->la_valid &= ~LA_ATIME;
2217         if ((valid & LA_CTIME) && (attr->la_ctime == LTIME_S(inode->i_ctime)))
2218                 attr->la_valid &= ~LA_CTIME;
2219         if ((valid & LA_MTIME) && (attr->la_mtime == LTIME_S(inode->i_mtime)))
2220                 attr->la_valid &= ~LA_MTIME;
2221
2222         result = osd_quota_transfer(inode, attr);
2223         if (result)
2224                 return;
2225
2226         if (attr->la_valid != 0) {
2227                 result = osd_inode_setattr(info->oti_env, inode, attr);
2228                 /*
2229                  * The osd_inode_setattr() should always succeed here.  The
2230                  * only error that could be returned is EDQUOT when we are
2231                  * trying to change the UID or GID of the inode. However, this
2232                  * should not happen since quota enforcement is no longer
2233                  * enabled on ldiskfs (lquota takes care of it).
2234                  */
2235                 LASSERTF(result == 0, "%d", result);
2236                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2237         }
2238
2239         attr->la_valid = valid;
2240 }
2241
2242 /**
2243  * Helper function for osd_object_create()
2244  *
2245  * \retval 0, on success
2246  */
2247 static int __osd_object_create(struct osd_thread_info *info,
2248                                struct osd_object *obj, struct lu_attr *attr,
2249                                struct dt_allocation_hint *hint,
2250                                struct dt_object_format *dof,
2251                                struct thandle *th)
2252 {
2253         int     result;
2254         __u32   umask;
2255
2256         /* we drop umask so that permissions we pass are not affected */
2257         umask = current->fs->umask;
2258         current->fs->umask = 0;
2259
2260         result = osd_create_type_f(dof->dof_type)(info, obj, attr, hint, dof,
2261                                                   th);
2262         if (result == 0) {
2263                 osd_attr_init(info, obj, attr, dof);
2264                 osd_object_init0(obj);
2265                 /* bz 24037 */
2266                 if (obj->oo_inode && (obj->oo_inode->i_state & I_NEW))
2267                         unlock_new_inode(obj->oo_inode);
2268         }
2269
2270         /* restore previous umask value */
2271         current->fs->umask = umask;
2272
2273         return result;
2274 }
2275
2276 /**
2277  * Helper function for osd_object_create()
2278  *
2279  * \retval 0, on success
2280  */
2281 static int __osd_oi_insert(const struct lu_env *env, struct osd_object *obj,
2282                            const struct lu_fid *fid, struct thandle *th)
2283 {
2284         struct osd_thread_info *info = osd_oti_get(env);
2285         struct osd_inode_id    *id   = &info->oti_id;
2286         struct osd_device      *osd  = osd_obj2dev(obj);
2287         struct osd_thandle     *oh;
2288
2289         LASSERT(obj->oo_inode != NULL);
2290
2291         oh = container_of0(th, struct osd_thandle, ot_super);
2292         LASSERT(oh->ot_handle);
2293
2294         osd_id_gen(id, obj->oo_inode->i_ino, obj->oo_inode->i_generation);
2295         return osd_oi_insert(info, osd, fid, id, oh->ot_handle, OI_CHECK_FLD);
2296 }
2297
2298 int osd_fld_lookup(const struct lu_env *env, struct osd_device *osd,
2299                    obd_seq seq, struct lu_seq_range *range)
2300 {
2301         struct seq_server_site  *ss = osd_seq_site(osd);
2302
2303         if (fid_seq_is_idif(seq)) {
2304                 fld_range_set_ost(range);
2305                 range->lsr_index = idif_ost_idx(seq);
2306                 return 0;
2307         }
2308
2309         if (!fid_seq_in_fldb(seq)) {
2310                 fld_range_set_mdt(range);
2311                 if (ss != NULL)
2312                         /* FIXME: If ss is NULL, it suppose not get lsr_index
2313                          * at all */
2314                         range->lsr_index = ss->ss_node_id;
2315                 return 0;
2316         }
2317
2318         LASSERT(ss != NULL);
2319         fld_range_set_any(range);
2320         /* OSD will only do local fld lookup */
2321         return fld_local_lookup(env, ss->ss_server_fld, seq, range);
2322 }
2323
2324 /*
2325  * Concurrency: no external locking is necessary.
2326  */
2327 static int osd_declare_object_create(const struct lu_env *env,
2328                                      struct dt_object *dt,
2329                                      struct lu_attr *attr,
2330                                      struct dt_allocation_hint *hint,
2331                                      struct dt_object_format *dof,
2332                                      struct thandle *handle)
2333 {
2334         struct osd_thandle      *oh;
2335         int                      rc;
2336         ENTRY;
2337
2338         LASSERT(handle != NULL);
2339
2340         oh = container_of0(handle, struct osd_thandle, ot_super);
2341         LASSERT(oh->ot_handle == NULL);
2342
2343         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
2344                              osd_dto_credits_noquota[DTO_OBJECT_CREATE]);
2345         if (!fid_is_on_ost(osd_oti_get(env), osd_dt_dev(handle->th_dev),
2346                            lu_object_fid(&dt->do_lu), OI_CHECK_FLD))
2347                 /* Reuse idle OI block may cause additional one OI block
2348                  * to be changed. */
2349                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
2350                                 osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
2351
2352         /* If this is directory, then we expect . and .. to be inserted as
2353          * well. The one directory block always needs to be created for the
2354          * directory, so we could use DTO_WRITE_BASE here (GDT, block bitmap,
2355          * block), there is no danger of needing a tree for the first block.
2356          */
2357         if (attr && S_ISDIR(attr->la_mode)) {
2358                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
2359                                      osd_dto_credits_noquota[DTO_WRITE_BASE]);
2360                 osd_trans_declare_op(env, oh, OSD_OT_INSERT, 0);
2361         }
2362
2363         if (!attr)
2364                 RETURN(0);
2365
2366         rc = osd_declare_inode_qid(env, attr->la_uid, attr->la_gid, 1, oh,
2367                                    false, false, NULL, false);
2368         if (rc != 0)
2369                 RETURN(rc);
2370
2371         RETURN(rc);
2372 }
2373
2374 static int osd_object_create(const struct lu_env *env, struct dt_object *dt,
2375                              struct lu_attr *attr,
2376                              struct dt_allocation_hint *hint,
2377                              struct dt_object_format *dof,
2378                              struct thandle *th)
2379 {
2380         const struct lu_fid    *fid    = lu_object_fid(&dt->do_lu);
2381         struct osd_object      *obj    = osd_dt_obj(dt);
2382         struct osd_thread_info *info   = osd_oti_get(env);
2383         int result;
2384
2385         ENTRY;
2386
2387         LINVRNT(osd_invariant(obj));
2388         LASSERT(!dt_object_exists(dt) && !dt_object_remote(dt));
2389         LASSERT(osd_write_locked(env, obj));
2390         LASSERT(th != NULL);
2391
2392         if (unlikely(fid_is_acct(fid)))
2393                 /* Quota files can't be created from the kernel any more,
2394                  * 'tune2fs -O quota' will take care of creating them */
2395                 RETURN(-EPERM);
2396
2397         osd_trans_exec_op(env, th, OSD_OT_CREATE);
2398         osd_trans_declare_rb(env, th, OSD_OT_REF_ADD);
2399
2400         result = __osd_object_create(info, obj, attr, hint, dof, th);
2401         if (result == 0)
2402                 result = __osd_oi_insert(env, obj, fid, th);
2403
2404         LASSERT(ergo(result == 0,
2405                      dt_object_exists(dt) && !dt_object_remote(dt)));
2406
2407         LASSERT(osd_invariant(obj));
2408         RETURN(result);
2409 }
2410
2411 /**
2412  * Called to destroy on-disk representation of the object
2413  *
2414  * Concurrency: must be locked
2415  */
2416 static int osd_declare_object_destroy(const struct lu_env *env,
2417                                       struct dt_object *dt,
2418                                       struct thandle *th)
2419 {
2420         struct osd_object  *obj = osd_dt_obj(dt);
2421         struct inode       *inode = obj->oo_inode;
2422         struct osd_thandle *oh;
2423         int                 rc;
2424         ENTRY;
2425
2426         oh = container_of0(th, struct osd_thandle, ot_super);
2427         LASSERT(oh->ot_handle == NULL);
2428         LASSERT(inode);
2429
2430         osd_trans_declare_op(env, oh, OSD_OT_DESTROY,
2431                              osd_dto_credits_noquota[DTO_OBJECT_DELETE]);
2432         /* Recycle idle OI leaf may cause additional three OI blocks
2433          * to be changed. */
2434         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
2435                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
2436         /* one less inode */
2437         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, -1, oh,
2438                                    false, true, NULL, false);
2439         if (rc)
2440                 RETURN(rc);
2441         /* data to be truncated */
2442         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0, oh,
2443                                    true, true, NULL, false);
2444         RETURN(rc);
2445 }
2446
2447 static int osd_object_destroy(const struct lu_env *env,
2448                               struct dt_object *dt,
2449                               struct thandle *th)
2450 {
2451         const struct lu_fid    *fid = lu_object_fid(&dt->do_lu);
2452         struct osd_object      *obj = osd_dt_obj(dt);
2453         struct inode           *inode = obj->oo_inode;
2454         struct osd_device      *osd = osd_obj2dev(obj);
2455         struct osd_thandle     *oh;
2456         int                     result;
2457         ENTRY;
2458
2459         oh = container_of0(th, struct osd_thandle, ot_super);
2460         LASSERT(oh->ot_handle);
2461         LASSERT(inode);
2462         LASSERT(!lu_object_is_dying(dt->do_lu.lo_header));
2463
2464         if (unlikely(fid_is_acct(fid)))
2465                 RETURN(-EPERM);
2466
2467         if (S_ISDIR(inode->i_mode)) {
2468                 LASSERT(osd_inode_unlinked(inode) || inode->i_nlink == 1 ||
2469                         inode->i_nlink == 2);
2470                 /* it will check/delete the inode from remote parent,
2471                  * how to optimize it? unlink performance impaction XXX */
2472                 result = osd_delete_from_remote_parent(env, osd, obj, oh);
2473                 if (result != 0 && result != -ENOENT) {
2474                         CERROR("%s: delete inode "DFID": rc = %d\n",
2475                                osd_name(osd), PFID(fid), result);
2476                 }
2477                 spin_lock(&obj->oo_guard);
2478                 clear_nlink(inode);
2479                 spin_unlock(&obj->oo_guard);
2480                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2481         }
2482
2483         osd_trans_exec_op(env, th, OSD_OT_DESTROY);
2484
2485         result = osd_oi_delete(osd_oti_get(env), osd, fid, oh->ot_handle,
2486                                OI_CHECK_FLD);
2487
2488         /* XXX: add to ext3 orphan list */
2489         /* rc = ext3_orphan_add(handle_t *handle, struct inode *inode) */
2490
2491         /* not needed in the cache anymore */
2492         set_bit(LU_OBJECT_HEARD_BANSHEE, &dt->do_lu.lo_header->loh_flags);
2493
2494         RETURN(0);
2495 }
2496
2497 /**
2498  * Put the fid into lustre_mdt_attrs, and then place the structure
2499  * inode's ea. This fid should not be altered during the life time
2500  * of the inode.
2501  *
2502  * \retval +ve, on success
2503  * \retval -ve, on error
2504  *
2505  * FIXME: It is good to have/use ldiskfs_xattr_set_handle() here
2506  */
2507 int osd_ea_fid_set(struct osd_thread_info *info, struct inode *inode,
2508                    const struct lu_fid *fid, __u32 compat, __u32 incompat)
2509 {
2510         struct lustre_mdt_attrs *lma = &info->oti_mdt_attrs;
2511         int                      rc;
2512         ENTRY;
2513
2514         if (OBD_FAIL_CHECK(OBD_FAIL_FID_INLMA))
2515                 RETURN(0);
2516
2517         lustre_lma_init(lma, fid, compat, incompat);
2518         lustre_lma_swab(lma);
2519
2520         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma, sizeof(*lma),
2521                              XATTR_CREATE);
2522         /* LMA may already exist, but we need to check that all the
2523          * desired compat/incompat flags have been added. */
2524         if (unlikely(rc == -EEXIST)) {
2525                 if (compat == 0 && incompat == 0)
2526                         RETURN(0);
2527
2528                 rc = __osd_xattr_get(inode, &info->oti_obj_dentry,
2529                                      XATTR_NAME_LMA, info->oti_mdt_attrs_old,
2530                                      LMA_OLD_SIZE);
2531                 if (rc <= 0)
2532                         RETURN(-EINVAL);
2533
2534                 lustre_lma_swab(lma);
2535                 if (!(~lma->lma_compat & compat) &&
2536                     !(~lma->lma_incompat & incompat))
2537                         RETURN(0);
2538
2539                 lma->lma_compat |= compat;
2540                 lma->lma_incompat |= incompat;
2541                 lustre_lma_swab(lma);
2542                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
2543                                      sizeof(*lma), XATTR_REPLACE);
2544         }
2545
2546         RETURN(rc);
2547 }
2548
2549 /**
2550  * ldiskfs supports fid in dirent, it is passed in dentry->d_fsdata.
2551  * lustre 1.8 also uses d_fsdata for passing other info to ldiskfs.
2552  * To have compatilibility with 1.8 ldiskfs driver we need to have
2553  * magic number at start of fid data.
2554  * \ldiskfs_dentry_param is used only to pass fid from osd to ldiskfs.
2555  * its inmemory API.
2556  */
2557 void osd_get_ldiskfs_dirent_param(struct ldiskfs_dentry_param *param,
2558                                   const struct dt_rec *fid)
2559 {
2560         if (!fid_is_namespace_visible((const struct lu_fid *)fid) ||
2561             OBD_FAIL_CHECK(OBD_FAIL_FID_IGIF)) {
2562                 param->edp_magic = 0;
2563                 return;
2564         }
2565
2566         param->edp_magic = LDISKFS_LUFID_MAGIC;
2567         param->edp_len =  sizeof(struct lu_fid) + 1;
2568         fid_cpu_to_be((struct lu_fid *)param->edp_data, (struct lu_fid *)fid);
2569 }
2570
2571 /**
2572  * Try to read the fid from inode ea into dt_rec.
2573  *
2574  * \param fid object fid.
2575  *
2576  * \retval 0 on success
2577  */
2578 static int osd_ea_fid_get(const struct lu_env *env, struct osd_object *obj,
2579                           __u32 ino, struct lu_fid *fid,
2580                           struct osd_inode_id *id)
2581 {
2582         struct osd_thread_info *info  = osd_oti_get(env);
2583         struct inode           *inode;
2584         ENTRY;
2585
2586         osd_id_gen(id, ino, OSD_OII_NOGEN);
2587         inode = osd_iget_fid(info, osd_obj2dev(obj), id, fid);
2588         if (IS_ERR(inode))
2589                 RETURN(PTR_ERR(inode));
2590
2591         iput(inode);
2592         RETURN(0);
2593 }
2594
2595 static int osd_add_dot_dotdot_internal(struct osd_thread_info *info,
2596                                         struct inode *dir,
2597                                         struct inode  *parent_dir,
2598                                         const struct dt_rec *dot_fid,
2599                                         const struct dt_rec *dot_dot_fid,
2600                                         struct osd_thandle *oth)
2601 {
2602         struct ldiskfs_dentry_param *dot_ldp;
2603         struct ldiskfs_dentry_param *dot_dot_ldp;
2604
2605         dot_dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp2;
2606         osd_get_ldiskfs_dirent_param(dot_dot_ldp, dot_dot_fid);
2607
2608         dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
2609         dot_ldp->edp_magic = 0;
2610         return ldiskfs_add_dot_dotdot(oth->ot_handle, parent_dir,
2611                                         dir, dot_ldp, dot_dot_ldp);
2612 }
2613
2614 /**
2615  * Create an local agent inode for remote entry
2616  */
2617 static struct inode *osd_create_local_agent_inode(const struct lu_env *env,
2618                                                   struct osd_device *osd,
2619                                                   struct osd_object *pobj,
2620                                                   const struct lu_fid *fid,
2621                                                   struct thandle *th)
2622 {
2623         struct osd_thread_info  *info = osd_oti_get(env);
2624         struct inode            *local;
2625         struct osd_thandle      *oh;
2626         int                     rc;
2627         ENTRY;
2628
2629         LASSERT(th);
2630         oh = container_of(th, struct osd_thandle, ot_super);
2631         LASSERT(oh->ot_handle->h_transaction != NULL);
2632
2633         /* FIXME: Insert index api needs to know the mode of
2634          * the remote object. Just use S_IFDIR for now */
2635         local = ldiskfs_create_inode(oh->ot_handle, pobj->oo_inode, S_IFDIR);
2636         if (IS_ERR(local)) {
2637                 CERROR("%s: create local error %d\n", osd_name(osd),
2638                        (int)PTR_ERR(local));
2639                 RETURN(local);
2640         }
2641
2642         ldiskfs_set_inode_state(local, LDISKFS_STATE_LUSTRE_NO_OI);
2643         /* Set special LMA flag for local agent inode */
2644         rc = osd_ea_fid_set(info, local, fid, 0, LMAI_AGENT);
2645         if (rc != 0) {
2646                 CERROR("%s: set LMA for "DFID" remote inode failed: rc = %d\n",
2647                        osd_name(osd), PFID(fid), rc);
2648                 RETURN(ERR_PTR(rc));
2649         }
2650
2651         rc = osd_add_dot_dotdot_internal(info, local, pobj->oo_inode,
2652                 (const struct dt_rec *)lu_object_fid(&pobj->oo_dt.do_lu),
2653                 (const struct dt_rec *)fid, oh);
2654         if (rc != 0) {
2655                 CERROR("%s: "DFID" add dot dotdot error: rc = %d\n",
2656                         osd_name(osd), PFID(fid), rc);
2657                 RETURN(ERR_PTR(rc));
2658         }
2659
2660         RETURN(local);
2661 }
2662
2663 /**
2664  * Delete local agent inode for remote entry
2665  */
2666 static int osd_delete_local_agent_inode(const struct lu_env *env,
2667                                         struct osd_device *osd,
2668                                         const struct lu_fid *fid,
2669                                         __u32 ino, struct osd_thandle *oh)
2670 {
2671         struct osd_thread_info  *oti = osd_oti_get(env);
2672         struct osd_inode_id     *id = &oti->oti_id;
2673         struct inode            *inode;
2674         ENTRY;
2675
2676         id->oii_ino = le32_to_cpu(ino);
2677         id->oii_gen = OSD_OII_NOGEN;
2678         inode = osd_iget(oti, osd, id);
2679         if (IS_ERR(inode)) {
2680                 CERROR("%s: iget error "DFID" id %u:%u\n", osd_name(osd),
2681                        PFID(fid), id->oii_ino, id->oii_gen);
2682                 RETURN(PTR_ERR(inode));
2683         }
2684
2685         clear_nlink(inode);
2686         mark_inode_dirty(inode);
2687         CDEBUG(D_INODE, "%s: delete remote inode "DFID" %lu\n",
2688                 osd_name(osd), PFID(fid), inode->i_ino);
2689         iput(inode);
2690         RETURN(0);
2691 }
2692
2693 /**
2694  * OSD layer object create function for interoperability mode (b11826).
2695  * This is mostly similar to osd_object_create(). Only difference being, fid is
2696  * inserted into inode ea here.
2697  *
2698  * \retval   0, on success
2699  * \retval -ve, on error
2700  */
2701 static int osd_object_ea_create(const struct lu_env *env, struct dt_object *dt,
2702                                 struct lu_attr *attr,
2703                                 struct dt_allocation_hint *hint,
2704                                 struct dt_object_format *dof,
2705                                 struct thandle *th)
2706 {
2707         const struct lu_fid    *fid    = lu_object_fid(&dt->do_lu);
2708         struct osd_object      *obj    = osd_dt_obj(dt);
2709         struct osd_thread_info *info   = osd_oti_get(env);
2710         int                     result;
2711
2712         ENTRY;
2713
2714         LASSERT(osd_invariant(obj));
2715         LASSERT(!dt_object_exists(dt) && !dt_object_remote(dt));
2716         LASSERT(osd_write_locked(env, obj));
2717         LASSERT(th != NULL);
2718
2719         if (unlikely(fid_is_acct(fid)))
2720                 /* Quota files can't be created from the kernel any more,
2721                  * 'tune2fs -O quota' will take care of creating them */
2722                 RETURN(-EPERM);
2723
2724         osd_trans_exec_op(env, th, OSD_OT_CREATE);
2725         osd_trans_declare_rb(env, th, OSD_OT_REF_ADD);
2726
2727         result = __osd_object_create(info, obj, attr, hint, dof, th);
2728         if (result == 0)
2729                 result = osd_ea_fid_set(info, obj->oo_inode, fid,
2730                                 fid_is_on_ost(info, osd_obj2dev(obj),
2731                                               fid, OI_CHECK_FLD) ?
2732                                 LMAC_FID_ON_OST : 0, 0);
2733
2734         if (result == 0)
2735                 result = __osd_oi_insert(env, obj, fid, th);
2736
2737         LASSERT(ergo(result == 0,
2738                      dt_object_exists(dt) && !dt_object_remote(dt)));
2739         LINVRNT(osd_invariant(obj));
2740         RETURN(result);
2741 }
2742
2743 static int osd_declare_object_ref_add(const struct lu_env *env,
2744                                       struct dt_object *dt,
2745                                       struct thandle *handle)
2746 {
2747         struct osd_thandle       *oh;
2748
2749         /* it's possible that object doesn't exist yet */
2750         LASSERT(handle != NULL);
2751
2752         oh = container_of0(handle, struct osd_thandle, ot_super);
2753         LASSERT(oh->ot_handle == NULL);
2754
2755         osd_trans_declare_op(env, oh, OSD_OT_REF_ADD,
2756                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2757
2758         return 0;
2759 }
2760
2761 /*
2762  * Concurrency: @dt is write locked.
2763  */
2764 static int osd_object_ref_add(const struct lu_env *env,
2765                               struct dt_object *dt, struct thandle *th)
2766 {
2767         struct osd_object  *obj = osd_dt_obj(dt);
2768         struct inode       *inode = obj->oo_inode;
2769         struct osd_thandle *oh;
2770         int                 rc = 0;
2771
2772         LINVRNT(osd_invariant(obj));
2773         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2774         LASSERT(osd_write_locked(env, obj));
2775         LASSERT(th != NULL);
2776
2777         oh = container_of0(th, struct osd_thandle, ot_super);
2778         LASSERT(oh->ot_handle != NULL);
2779
2780         osd_trans_exec_op(env, th, OSD_OT_REF_ADD);
2781
2782         /*
2783          * The DIR_NLINK feature allows directories to exceed LDISKFS_LINK_MAX
2784          * (65000) subdirectories by storing "1" in i_nlink if the link count
2785          * would otherwise overflow. Directory tranversal tools understand
2786          * that (st_nlink == 1) indicates that the filesystem dose not track
2787          * hard links count on the directory, and will not abort subdirectory
2788          * scanning early once (st_nlink - 2) subdirs have been found.
2789          *
2790          * This also has to properly handle the case of inodes with nlink == 0
2791          * in case they are being linked into the PENDING directory
2792          */
2793         spin_lock(&obj->oo_guard);
2794         ldiskfs_inc_count(oh->ot_handle, inode);
2795         LASSERT(inode->i_nlink <= LDISKFS_LINK_MAX);
2796         spin_unlock(&obj->oo_guard);
2797
2798         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2799         LINVRNT(osd_invariant(obj));
2800
2801         return rc;
2802 }
2803
2804 static int osd_declare_object_ref_del(const struct lu_env *env,
2805                                       struct dt_object *dt,
2806                                       struct thandle *handle)
2807 {
2808         struct osd_thandle *oh;
2809
2810         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2811         LASSERT(handle != NULL);
2812
2813         oh = container_of0(handle, struct osd_thandle, ot_super);
2814         LASSERT(oh->ot_handle == NULL);
2815
2816         osd_trans_declare_op(env, oh, OSD_OT_REF_DEL,
2817                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2818
2819         return 0;
2820 }
2821
2822 /*
2823  * Concurrency: @dt is write locked.
2824  */
2825 static int osd_object_ref_del(const struct lu_env *env, struct dt_object *dt,
2826                               struct thandle *th)
2827 {
2828         struct osd_object       *obj = osd_dt_obj(dt);
2829         struct inode            *inode = obj->oo_inode;
2830         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
2831         struct osd_thandle      *oh;
2832
2833         LINVRNT(osd_invariant(obj));
2834         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2835         LASSERT(osd_write_locked(env, obj));
2836         LASSERT(th != NULL);
2837
2838         oh = container_of0(th, struct osd_thandle, ot_super);
2839         LASSERT(oh->ot_handle != NULL);
2840
2841         osd_trans_exec_op(env, th, OSD_OT_REF_DEL);
2842
2843         spin_lock(&obj->oo_guard);
2844         /* That can be result of upgrade from old Lustre version and
2845          * applied only to local files.  Just skip this ref_del call.
2846          * ext4_unlink() only treats this as a warning, don't LASSERT here.*/
2847         if (inode->i_nlink == 0) {
2848                 CDEBUG_LIMIT(fid_is_norm(lu_object_fid(&dt->do_lu)) ?
2849                              D_ERROR : D_INODE, "%s: nlink == 0 on "DFID
2850                              ", maybe an upgraded file? (LU-3915)\n",
2851                              osd_name(osd), PFID(lu_object_fid(&dt->do_lu)));
2852                 spin_unlock(&obj->oo_guard);
2853                 return 0;
2854         }
2855
2856         ldiskfs_dec_count(oh->ot_handle, inode);
2857         spin_unlock(&obj->oo_guard);
2858
2859         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2860         LINVRNT(osd_invariant(obj));
2861
2862         return 0;
2863 }
2864
2865 /*
2866  * Get the 64-bit version for an inode.
2867  */
2868 static int osd_object_version_get(const struct lu_env *env,
2869                                   struct dt_object *dt, dt_obj_version_t *ver)
2870 {
2871         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2872
2873         CDEBUG(D_INODE, "Get version "LPX64" for inode %lu\n",
2874                LDISKFS_I(inode)->i_fs_version, inode->i_ino);
2875         *ver = LDISKFS_I(inode)->i_fs_version;
2876         return 0;
2877 }
2878
2879 /*
2880  * Concurrency: @dt is read locked.
2881  */
2882 static int osd_xattr_get(const struct lu_env *env, struct dt_object *dt,
2883                          struct lu_buf *buf, const char *name,
2884                          struct lustre_capa *capa)
2885 {
2886         struct osd_object      *obj    = osd_dt_obj(dt);
2887         struct inode           *inode  = obj->oo_inode;
2888         struct osd_thread_info *info   = osd_oti_get(env);
2889         struct dentry          *dentry = &info->oti_obj_dentry;
2890
2891         /* version get is not real XATTR but uses xattr API */
2892         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2893                 /* for version we are just using xattr API but change inode
2894                  * field instead */
2895                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
2896                 osd_object_version_get(env, dt, buf->lb_buf);
2897                 return sizeof(dt_obj_version_t);
2898         }
2899
2900         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2901         LASSERT(inode->i_op != NULL && inode->i_op->getxattr != NULL);
2902
2903         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
2904                 return -EACCES;
2905
2906         return __osd_xattr_get(inode, dentry, name, buf->lb_buf, buf->lb_len);
2907 }
2908
2909
2910 static int osd_declare_xattr_set(const struct lu_env *env,
2911                                  struct dt_object *dt,
2912                                  const struct lu_buf *buf, const char *name,
2913                                  int fl, struct thandle *handle)
2914 {
2915         struct osd_thandle *oh;
2916
2917         LASSERT(handle != NULL);
2918
2919         oh = container_of0(handle, struct osd_thandle, ot_super);
2920         LASSERT(oh->ot_handle == NULL);
2921
2922         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2923                              strcmp(name, XATTR_NAME_VERSION) == 0 ?
2924                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE] :
2925                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2926
2927         return 0;
2928 }
2929
2930 /*
2931  * Set the 64-bit version for object
2932  */
2933 static void osd_object_version_set(const struct lu_env *env,
2934                                    struct dt_object *dt,
2935                                    dt_obj_version_t *new_version)
2936 {
2937         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2938
2939         CDEBUG(D_INODE, "Set version "LPX64" (old "LPX64") for inode %lu\n",
2940                *new_version, LDISKFS_I(inode)->i_fs_version, inode->i_ino);
2941
2942         LDISKFS_I(inode)->i_fs_version = *new_version;
2943         /** Version is set after all inode operations are finished,
2944          *  so we should mark it dirty here */
2945         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2946 }
2947
2948 /*
2949  * Concurrency: @dt is write locked.
2950  */
2951 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
2952                          const struct lu_buf *buf, const char *name, int fl,
2953                          struct thandle *handle, struct lustre_capa *capa)
2954 {
2955         struct osd_object      *obj      = osd_dt_obj(dt);
2956         struct inode           *inode    = obj->oo_inode;
2957         struct osd_thread_info *info     = osd_oti_get(env);
2958         int                     fs_flags = 0;
2959         ENTRY;
2960
2961         LASSERT(handle != NULL);
2962
2963         /* version set is not real XATTR */
2964         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2965                 /* for version we are just using xattr API but change inode
2966                  * field instead */
2967                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
2968                 osd_object_version_set(env, dt, buf->lb_buf);
2969                 return sizeof(dt_obj_version_t);
2970         }
2971
2972         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
2973                 return -EACCES;
2974
2975         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
2976         if (fl & LU_XATTR_REPLACE)
2977                 fs_flags |= XATTR_REPLACE;
2978
2979         if (fl & LU_XATTR_CREATE)
2980                 fs_flags |= XATTR_CREATE;
2981
2982         return __osd_xattr_set(info, inode, name, buf->lb_buf, buf->lb_len,
2983                                fs_flags);
2984 }
2985
2986 /*
2987  * Concurrency: @dt is read locked.
2988  */
2989 static int osd_xattr_list(const struct lu_env *env, struct dt_object *dt,
2990                           struct lu_buf *buf, struct lustre_capa *capa)
2991 {
2992         struct osd_object      *obj    = osd_dt_obj(dt);
2993         struct inode           *inode  = obj->oo_inode;
2994         struct osd_thread_info *info   = osd_oti_get(env);
2995         struct dentry          *dentry = &info->oti_obj_dentry;
2996
2997         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2998         LASSERT(inode->i_op != NULL && inode->i_op->listxattr != NULL);
2999         LASSERT(osd_read_locked(env, obj) || osd_write_locked(env, obj));
3000
3001         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
3002                 return -EACCES;
3003
3004         dentry->d_inode = inode;
3005         dentry->d_sb = inode->i_sb;
3006         return inode->i_op->listxattr(dentry, buf->lb_buf, buf->lb_len);
3007 }
3008
3009 static int osd_declare_xattr_del(const struct lu_env *env,
3010                                  struct dt_object *dt, const char *name,
3011                                  struct thandle *handle)
3012 {
3013         struct osd_thandle *oh;
3014
3015         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3016         LASSERT(handle != NULL);
3017
3018         oh = container_of0(handle, struct osd_thandle, ot_super);
3019         LASSERT(oh->ot_handle == NULL);
3020
3021         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
3022                              osd_dto_credits_noquota[DTO_XATTR_SET]);
3023
3024         return 0;
3025 }
3026
3027 /*
3028  * Concurrency: @dt is write locked.
3029  */
3030 static int osd_xattr_del(const struct lu_env *env, struct dt_object *dt,
3031                          const char *name, struct thandle *handle,
3032                          struct lustre_capa *capa)
3033 {
3034         struct osd_object      *obj    = osd_dt_obj(dt);
3035         struct inode           *inode  = obj->oo_inode;
3036         struct osd_thread_info *info   = osd_oti_get(env);
3037         struct dentry          *dentry = &info->oti_obj_dentry;
3038         int                     rc;
3039
3040         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3041         LASSERT(inode->i_op != NULL && inode->i_op->removexattr != NULL);
3042         LASSERT(handle != NULL);
3043
3044         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
3045                 return -EACCES;
3046
3047         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
3048
3049         ll_vfs_dq_init(inode);
3050         dentry->d_inode = inode;
3051         dentry->d_sb = inode->i_sb;
3052         rc = inode->i_op->removexattr(dentry, name);
3053         return rc;
3054 }
3055
3056 static struct obd_capa *osd_capa_get(const struct lu_env *env,
3057                                      struct dt_object *dt,
3058                                      struct lustre_capa *old, __u64 opc)
3059 {
3060         struct osd_thread_info *info = osd_oti_get(env);
3061         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
3062         struct osd_object *obj = osd_dt_obj(dt);
3063         struct osd_device *osd = osd_obj2dev(obj);
3064         struct lustre_capa_key *key = &info->oti_capa_key;
3065         struct lustre_capa *capa = &info->oti_capa;
3066         struct obd_capa *oc;
3067         struct lu_capainfo *lci;
3068         int rc;
3069         ENTRY;
3070
3071         if (!osd->od_fl_capa)
3072                 RETURN(ERR_PTR(-ENOENT));
3073
3074         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3075         LINVRNT(osd_invariant(obj));
3076
3077         /* renewal sanity check */
3078         if (old && osd_object_auth(env, dt, old, opc))
3079                 RETURN(ERR_PTR(-EACCES));
3080
3081         lci = lu_capainfo_get(env);
3082         if (unlikely(lci == NULL))
3083                 RETURN(ERR_PTR(-ENOENT));
3084
3085         switch (lci->lci_auth) {
3086         case LC_ID_NONE:
3087                 RETURN(NULL);
3088         case LC_ID_PLAIN:
3089                 capa->lc_uid = obj->oo_inode->i_uid;
3090                 capa->lc_gid = obj->oo_inode->i_gid;
3091                 capa->lc_flags = LC_ID_PLAIN;
3092                 break;
3093         case LC_ID_CONVERT: {
3094                 __u32 d[4], s[4];
3095
3096                 s[0] = obj->oo_inode->i_uid;
3097                 cfs_get_random_bytes(&(s[1]), sizeof(__u32));
3098                 s[2] = obj->oo_inode->i_gid;
3099                 cfs_get_random_bytes(&(s[3]), sizeof(__u32));
3100                 rc = capa_encrypt_id(d, s, key->lk_key, CAPA_HMAC_KEY_MAX_LEN);
3101                 if (unlikely(rc))
3102                         RETURN(ERR_PTR(rc));
3103
3104                 capa->lc_uid   = ((__u64)d[1] << 32) | d[0];
3105                 capa->lc_gid   = ((__u64)d[3] << 32) | d[2];
3106                 capa->lc_flags = LC_ID_CONVERT;
3107                 break;
3108         }
3109         default:
3110                 RETURN(ERR_PTR(-EINVAL));
3111         }
3112
3113         capa->lc_fid = *fid;
3114         capa->lc_opc = opc;
3115         capa->lc_flags |= osd->od_capa_alg << 24;
3116         capa->lc_timeout = osd->od_capa_timeout;
3117         capa->lc_expiry = 0;
3118
3119         oc = capa_lookup(osd->od_capa_hash, capa, 1);
3120         if (oc) {
3121                 LASSERT(!capa_is_expired(oc));
3122                 RETURN(oc);
3123         }
3124
3125         spin_lock(&capa_lock);
3126         *key = osd->od_capa_keys[1];
3127         spin_unlock(&capa_lock);
3128
3129         capa->lc_keyid = key->lk_keyid;
3130         capa->lc_expiry = cfs_time_current_sec() + osd->od_capa_timeout;
3131
3132         rc = capa_hmac(capa->lc_hmac, capa, key->lk_key);
3133         if (rc) {
3134                 DEBUG_CAPA(D_ERROR, capa, "HMAC failed: %d for", rc);
3135                 RETURN(ERR_PTR(rc));
3136         }
3137
3138         oc = capa_add(osd->od_capa_hash, capa);
3139         RETURN(oc);
3140 }
3141
3142 static int osd_object_sync(const struct lu_env *env, struct dt_object *dt)
3143 {
3144         struct osd_object       *obj    = osd_dt_obj(dt);
3145         struct inode            *inode  = obj->oo_inode;
3146         struct osd_thread_info  *info   = osd_oti_get(env);
3147         struct dentry           *dentry = &info->oti_obj_dentry;
3148         struct file             *file   = &info->oti_file;
3149         int                     rc;
3150
3151         ENTRY;
3152
3153         dentry->d_inode = inode;
3154         dentry->d_sb = inode->i_sb;
3155         file->f_dentry = dentry;
3156         file->f_mapping = inode->i_mapping;
3157         file->f_op = inode->i_fop;
3158         set_file_inode(file, inode);
3159 #ifndef HAVE_FILE_FSYNC_4ARGS
3160         mutex_lock(&inode->i_mutex);
3161 #endif
3162         rc = do_fsync(file, 0);
3163 #ifndef HAVE_FILE_FSYNC_4ARGS
3164         mutex_unlock(&inode->i_mutex);
3165 #endif
3166         RETURN(rc);
3167 }
3168
3169 static int osd_data_get(const struct lu_env *env, struct dt_object *dt,
3170                         void **data)
3171 {
3172         struct osd_object *obj = osd_dt_obj(dt);
3173         ENTRY;
3174
3175         *data = (void *)obj->oo_inode;
3176         RETURN(0);
3177 }
3178
3179 /*
3180  * Index operations.
3181  */
3182
3183 static int osd_iam_index_probe(const struct lu_env *env, struct osd_object *o,
3184                            const struct dt_index_features *feat)
3185 {
3186         struct iam_descr *descr;
3187
3188         if (osd_object_is_root(o))
3189                 return feat == &dt_directory_features;
3190
3191         LASSERT(o->oo_dir != NULL);
3192
3193         descr = o->oo_dir->od_container.ic_descr;
3194         if (feat == &dt_directory_features) {
3195                 if (descr->id_rec_size == sizeof(struct osd_fid_pack))
3196                         return 1;
3197                 else
3198                         return 0;
3199         } else {
3200                 return
3201                         feat->dif_keysize_min <= descr->id_key_size &&
3202                         descr->id_key_size <= feat->dif_keysize_max &&
3203                         feat->dif_recsize_min <= descr->id_rec_size &&
3204                         descr->id_rec_size <= feat->dif_recsize_max &&
3205                         !(feat->dif_flags & (DT_IND_VARKEY |
3206                                              DT_IND_VARREC | DT_IND_NONUNQ)) &&
3207                         ergo(feat->dif_flags & DT_IND_UPDATE,
3208                              1 /* XXX check that object (and file system) is
3209                                 * writable */);
3210         }
3211 }
3212
3213 static int osd_iam_container_init(const struct lu_env *env,
3214                                   struct osd_object *obj,
3215                                   struct osd_directory *dir)
3216 {
3217         struct iam_container *bag = &dir->od_container;
3218         int result;
3219
3220         result = iam_container_init(bag, &dir->od_descr, obj->oo_inode);
3221         if (result != 0)
3222                 return result;
3223
3224         result = iam_container_setup(bag);
3225         if (result == 0)
3226                 obj->oo_dt.do_index_ops = &osd_index_iam_ops;
3227         else
3228                 iam_container_fini(bag);
3229
3230         return result;
3231 }
3232
3233
3234 /*
3235  * Concurrency: no external locking is necessary.
3236  */
3237 static int osd_index_try(const struct lu_env *env, struct dt_object *dt,
3238                          const struct dt_index_features *feat)
3239 {
3240         int                      result;
3241         int                      skip_iam = 0;
3242         struct osd_object       *obj = osd_dt_obj(dt);
3243
3244         LINVRNT(osd_invariant(obj));
3245
3246         if (osd_object_is_root(obj)) {
3247                 dt->do_index_ops = &osd_index_ea_ops;
3248                 result = 0;
3249         } else if (feat == &dt_directory_features) {
3250                 dt->do_index_ops = &osd_index_ea_ops;
3251                 if (obj->oo_inode != NULL && S_ISDIR(obj->oo_inode->i_mode))
3252                         result = 0;
3253                 else
3254                         result = -ENOTDIR;
3255                 skip_iam = 1;
3256         } else if (unlikely(feat == &dt_otable_features)) {
3257                 dt->do_index_ops = &osd_otable_ops;
3258                 return 0;
3259         } else if (unlikely(feat == &dt_acct_features)) {
3260                 dt->do_index_ops = &osd_acct_index_ops;
3261                 result = 0;
3262                 skip_iam = 1;
3263         } else if (!osd_has_index(obj)) {
3264                 struct osd_directory *dir;
3265
3266                 OBD_ALLOC_PTR(dir);
3267                 if (dir != NULL) {
3268
3269                         spin_lock(&obj->oo_guard);
3270                         if (obj->oo_dir == NULL)
3271                                 obj->oo_dir = dir;
3272                         else
3273                                 /*
3274                                  * Concurrent thread allocated container data.
3275                                  */
3276                                 OBD_FREE_PTR(dir);
3277                         spin_unlock(&obj->oo_guard);
3278                         /*
3279                          * Now, that we have container data, serialize its
3280                          * initialization.
3281                          */
3282                         down_write(&obj->oo_ext_idx_sem);
3283                         /*
3284                          * recheck under lock.
3285                          */
3286                         if (!osd_has_index(obj))
3287                                 result = osd_iam_container_init(env, obj, dir);
3288                         else
3289                                 result = 0;
3290                         up_write(&obj->oo_ext_idx_sem);
3291                 } else {
3292                         result = -ENOMEM;
3293                 }
3294         } else {
3295                 result = 0;
3296         }
3297
3298         if (result == 0 && skip_iam == 0) {
3299                 if (!osd_iam_index_probe(env, obj, feat))
3300                         result = -ENOTDIR;
3301         }
3302         LINVRNT(osd_invariant(obj));
3303
3304         if (result == 0 && is_quota_glb_feat(feat) &&
3305             fid_seq(lu_object_fid(&dt->do_lu)) == FID_SEQ_QUOTA_GLB)
3306                 result = osd_quota_migration(env, dt, feat);
3307
3308         return result;
3309 }
3310
3311 static int osd_otable_it_attr_get(const struct lu_env *env,
3312                                  struct dt_object *dt,
3313                                  struct lu_attr *attr,
3314                                  struct lustre_capa *capa)
3315 {
3316         attr->la_valid = 0;
3317         return 0;
3318 }
3319
3320 static const struct dt_object_operations osd_obj_ops = {
3321         .do_read_lock         = osd_object_read_lock,
3322         .do_write_lock        = osd_object_write_lock,
3323         .do_read_unlock       = osd_object_read_unlock,
3324         .do_write_unlock      = osd_object_write_unlock,
3325         .do_write_locked      = osd_object_write_locked,
3326         .do_attr_get          = osd_attr_get,
3327         .do_declare_attr_set  = osd_declare_attr_set,
3328         .do_attr_set          = osd_attr_set,
3329         .do_ah_init           = osd_ah_init,
3330         .do_declare_create    = osd_declare_object_create,
3331         .do_create            = osd_object_create,
3332         .do_declare_destroy   = osd_declare_object_destroy,
3333         .do_destroy           = osd_object_destroy,
3334         .do_index_try         = osd_index_try,
3335         .do_declare_ref_add   = osd_declare_object_ref_add,
3336         .do_ref_add           = osd_object_ref_add,
3337         .do_declare_ref_del   = osd_declare_object_ref_del,
3338         .do_ref_del           = osd_object_ref_del,
3339         .do_xattr_get         = osd_xattr_get,
3340         .do_declare_xattr_set = osd_declare_xattr_set,
3341         .do_xattr_set         = osd_xattr_set,
3342         .do_declare_xattr_del = osd_declare_xattr_del,
3343         .do_xattr_del         = osd_xattr_del,
3344         .do_xattr_list        = osd_xattr_list,
3345         .do_capa_get          = osd_capa_get,
3346         .do_object_sync       = osd_object_sync,
3347         .do_data_get          = osd_data_get,
3348 };
3349
3350 /**
3351  * dt_object_operations for interoperability mode
3352  * (i.e. to run 2.0 mds on 1.8 disk) (b11826)
3353  */
3354 static const struct dt_object_operations osd_obj_ea_ops = {
3355         .do_read_lock         = osd_object_read_lock,
3356         .do_write_lock        = osd_object_write_lock,
3357         .do_read_unlock       = osd_object_read_unlock,
3358         .do_write_unlock      = osd_object_write_unlock,
3359         .do_write_locked      = osd_object_write_locked,
3360         .do_attr_get          = osd_attr_get,
3361         .do_declare_attr_set  = osd_declare_attr_set,
3362         .do_attr_set          = osd_attr_set,
3363         .do_ah_init           = osd_ah_init,
3364         .do_declare_create    = osd_declare_object_create,
3365         .do_create            = osd_object_ea_create,
3366         .do_declare_destroy   = osd_declare_object_destroy,
3367         .do_destroy           = osd_object_destroy,
3368         .do_index_try         = osd_index_try,
3369         .do_declare_ref_add   = osd_declare_object_ref_add,
3370         .do_ref_add           = osd_object_ref_add,
3371         .do_declare_ref_del   = osd_declare_object_ref_del,
3372         .do_ref_del           = osd_object_ref_del,
3373         .do_xattr_get         = osd_xattr_get,
3374         .do_declare_xattr_set = osd_declare_xattr_set,
3375         .do_xattr_set         = osd_xattr_set,
3376         .do_declare_xattr_del = osd_declare_xattr_del,
3377         .do_xattr_del         = osd_xattr_del,
3378         .do_xattr_list        = osd_xattr_list,
3379         .do_capa_get          = osd_capa_get,
3380         .do_object_sync       = osd_object_sync,
3381         .do_data_get          = osd_data_get,
3382 };
3383
3384 static const struct dt_object_operations osd_obj_otable_it_ops = {
3385         .do_attr_get    = osd_otable_it_attr_get,
3386         .do_index_try   = osd_index_try,
3387 };
3388
3389 static int osd_index_declare_iam_delete(const struct lu_env *env,
3390                                         struct dt_object *dt,
3391                                         const struct dt_key *key,
3392                                         struct thandle *handle)
3393 {
3394         struct osd_thandle    *oh;
3395
3396         oh = container_of0(handle, struct osd_thandle, ot_super);
3397         LASSERT(oh->ot_handle == NULL);
3398
3399         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3400                              osd_dto_credits_noquota[DTO_INDEX_DELETE]);
3401
3402         return 0;
3403 }
3404
3405 /**
3406  *      delete a (key, value) pair from index \a dt specified by \a key
3407  *
3408  *      \param  dt      osd index object
3409  *      \param  key     key for index
3410  *      \param  rec     record reference
3411  *      \param  handle  transaction handler
3412  *
3413  *      \retval  0  success
3414  *      \retval -ve   failure
3415  */
3416
3417 static int osd_index_iam_delete(const struct lu_env *env, struct dt_object *dt,
3418                                 const struct dt_key *key,
3419                                 struct thandle *handle,
3420                                 struct lustre_capa *capa)
3421 {
3422         struct osd_thread_info *oti = osd_oti_get(env);
3423         struct osd_object      *obj = osd_dt_obj(dt);
3424         struct osd_thandle     *oh;
3425         struct iam_path_descr  *ipd;
3426         struct iam_container   *bag = &obj->oo_dir->od_container;
3427         int                     rc;
3428
3429         ENTRY;
3430
3431         LINVRNT(osd_invariant(obj));
3432         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3433         LASSERT(bag->ic_object == obj->oo_inode);
3434         LASSERT(handle != NULL);
3435
3436         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
3437                 RETURN(-EACCES);
3438
3439         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3440
3441         ipd = osd_idx_ipd_get(env, bag);
3442         if (unlikely(ipd == NULL))
3443                 RETURN(-ENOMEM);
3444
3445         oh = container_of0(handle, struct osd_thandle, ot_super);
3446         LASSERT(oh->ot_handle != NULL);
3447         LASSERT(oh->ot_handle->h_transaction != NULL);
3448
3449         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3450                 /* swab quota uid/gid provided by caller */
3451                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3452                 key = (const struct dt_key *)&oti->oti_quota_id;
3453         }
3454
3455         rc = iam_delete(oh->ot_handle, bag, (const struct iam_key *)key, ipd);
3456         osd_ipd_put(env, bag, ipd);
3457         LINVRNT(osd_invariant(obj));
3458         RETURN(rc);
3459 }
3460
3461 static int osd_index_declare_ea_delete(const struct lu_env *env,
3462                                        struct dt_object *dt,
3463                                        const struct dt_key *key,
3464                                        struct thandle *handle)
3465 {
3466         struct osd_thandle *oh;
3467         struct inode       *inode;
3468         int                 rc;
3469         ENTRY;
3470
3471         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3472         LASSERT(handle != NULL);
3473
3474         oh = container_of0(handle, struct osd_thandle, ot_super);
3475         LASSERT(oh->ot_handle == NULL);
3476
3477         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3478                              osd_dto_credits_noquota[DTO_INDEX_DELETE]);
3479
3480         inode = osd_dt_obj(dt)->oo_inode;
3481         LASSERT(inode);
3482
3483         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0, oh,
3484                                    true, true, NULL, false);
3485         RETURN(rc);
3486 }
3487
3488 static inline int osd_get_fid_from_dentry(struct ldiskfs_dir_entry_2 *de,
3489                                           struct dt_rec *fid)
3490 {
3491         struct osd_fid_pack *rec;
3492         int                  rc = -ENODATA;
3493
3494         if (de->file_type & LDISKFS_DIRENT_LUFID) {
3495                 rec = (struct osd_fid_pack *) (de->name + de->name_len + 1);
3496                 rc = osd_fid_unpack((struct lu_fid *)fid, rec);
3497         }
3498         return rc;
3499 }
3500
3501 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
3502                           struct lu_fid *fid)
3503 {
3504         ENTRY;
3505
3506         /* FID seqs not in FLDB, must be local seq */
3507         if (unlikely(!fid_seq_in_fldb(fid_seq(fid))))
3508                 RETURN(0);
3509
3510         if (osd_seq_exists(env, osd, fid_seq(fid)))
3511                 RETURN(0);
3512
3513         RETURN(1);
3514 }
3515
3516 /**
3517  * Index delete function for interoperability mode (b11826).
3518  * It will remove the directory entry added by osd_index_ea_insert().
3519  * This entry is needed to maintain name->fid mapping.
3520  *
3521  * \param key,  key i.e. file entry to be deleted
3522  *
3523  * \retval   0, on success
3524  * \retval -ve, on error
3525  */
3526 static int osd_index_ea_delete(const struct lu_env *env, struct dt_object *dt,
3527                                const struct dt_key *key,
3528                                struct thandle *handle,
3529                                struct lustre_capa *capa)
3530 {
3531         struct osd_object          *obj    = osd_dt_obj(dt);
3532         struct inode               *dir    = obj->oo_inode;
3533         struct dentry              *dentry;
3534         struct osd_thandle         *oh;
3535         struct ldiskfs_dir_entry_2 *de = NULL;
3536         struct buffer_head         *bh;
3537         struct htree_lock          *hlock = NULL;
3538         struct lu_fid              *fid = &osd_oti_get(env)->oti_fid;
3539         struct osd_device          *osd = osd_dev(dt->do_lu.lo_dev);
3540         int                        rc;
3541         ENTRY;
3542
3543         LINVRNT(osd_invariant(obj));
3544         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3545         LASSERT(handle != NULL);
3546
3547         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3548
3549         oh = container_of(handle, struct osd_thandle, ot_super);
3550         LASSERT(oh->ot_handle != NULL);
3551         LASSERT(oh->ot_handle->h_transaction != NULL);
3552
3553         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
3554                 RETURN(-EACCES);
3555
3556         ll_vfs_dq_init(dir);
3557         dentry = osd_child_dentry_get(env, obj,
3558                                       (char *)key, strlen((char *)key));
3559
3560         if (obj->oo_hl_head != NULL) {
3561                 hlock = osd_oti_get(env)->oti_hlock;
3562                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
3563                                    dir, LDISKFS_HLOCK_DEL);
3564         } else {
3565                 down_write(&obj->oo_ext_idx_sem);
3566         }
3567
3568         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
3569         if (bh) {
3570                 __u32 ino = 0;
3571
3572                 /* If this is not the ".." entry, it might be a remote DNE
3573                  * entry and  we need to check if the FID is for a remote
3574                  * MDT.  If the FID is  not in the directory entry (e.g.
3575                  * upgraded 1.8 filesystem without dirdata enabled) then
3576                  * we need to get the FID from the LMA. For a remote directory
3577                  * there HAS to be an LMA, it cannot be an IGIF inode in this
3578                  * case.
3579                  *
3580                  * Delete the entry before the agent inode in order to
3581                  * simplify error handling.  At worst an error after deleting
3582                  * the entry first might leak the agent inode afterward. The
3583                  * reverse would need filesystem abort in case of error deleting
3584                  * the entry after the agent had been removed, or leave a
3585                  * dangling entry pointing at a random inode. */
3586                 if (strcmp((char *)key, dotdot) != 0) {
3587                         LASSERT(de != NULL);
3588                         rc = osd_get_fid_from_dentry(de, (struct dt_rec *)fid);
3589                         /* If Fid is not in dentry, try to get it from LMA */
3590                         if (rc == -ENODATA) {
3591                                 struct osd_inode_id *id;
3592                                 struct inode *inode;
3593
3594                                 /* Before trying to get fid from the inode,
3595                                  * check whether the inode is valid.
3596                                  *
3597                                  * If the inode has been deleted, do not go
3598                                  * ahead to do osd_ea_fid_get, which will set
3599                                  * the inode to bad inode, which might cause
3600                                  * the inode to be deleted uncorrectly */
3601                                 inode = ldiskfs_iget(osd_sb(osd),
3602                                                      le32_to_cpu(de->inode));
3603                                 if (IS_ERR(inode)) {
3604                                         CDEBUG(D_INODE, "%s: "DFID"get inode"
3605                                                "error.\n", osd_name(osd),
3606                                                PFID(fid));
3607                                         rc = PTR_ERR(inode);
3608                                 } else {
3609                                         if (likely(inode->i_nlink != 0)) {
3610                                                 id = &osd_oti_get(env)->oti_id;
3611                                                 rc = osd_ea_fid_get(env, obj,
3612                                                         le32_to_cpu(de->inode),
3613                                                                     fid, id);
3614                                         } else {
3615                                                 CDEBUG(D_INFO, "%s: %u "DFID
3616                                                        "deleted.\n",
3617                                                        osd_name(osd),
3618                                                        le32_to_cpu(de->inode),
3619                                                        PFID(fid));
3620                                                 rc = -ESTALE;
3621                                         }
3622                                         iput(inode);
3623                                 }
3624                         }
3625                         if (rc == 0 &&
3626                             unlikely(osd_remote_fid(env, osd, fid)))
3627                                 /* Need to delete agent inode */
3628                                 ino = le32_to_cpu(de->inode);
3629                 }
3630                 rc = ldiskfs_delete_entry(oh->ot_handle, dir, de, bh);
3631                 brelse(bh);
3632                 if (rc == 0 && unlikely(ino != 0)) {
3633                         rc = osd_delete_local_agent_inode(env, osd, fid, ino,
3634                                                           oh);
3635                         if (rc != 0)
3636                                 CERROR("%s: del local inode "DFID": rc = %d\n",
3637                                        osd_name(osd), PFID(fid), rc);
3638                 }
3639         } else {
3640                 rc = -ENOENT;
3641         }
3642         if (hlock != NULL)
3643                 ldiskfs_htree_unlock(hlock);
3644         else
3645                 up_write(&obj->oo_ext_idx_sem);
3646
3647         if (rc != 0)
3648                 GOTO(out, rc);
3649
3650         /* For inode on the remote MDT, .. will point to
3651          * /Agent directory, Check whether it needs to delete
3652          * from agent directory */
3653         if (unlikely(strcmp((char *)key, dotdot) == 0)) {
3654                 rc = osd_delete_from_remote_parent(env, osd_obj2dev(obj), obj,
3655                                                    oh);
3656                 if (rc != 0 && rc != -ENOENT) {
3657                         CERROR("%s: delete agent inode "DFID": rc = %d\n",
3658                                osd_name(osd), PFID(fid), rc);
3659                 }
3660
3661                 if (rc == -ENOENT)
3662                         rc = 0;
3663
3664                 GOTO(out, rc);
3665         }
3666 out:
3667
3668         LASSERT(osd_invariant(obj));
3669         RETURN(rc);
3670 }
3671
3672 /**
3673  *      Lookup index for \a key and copy record to \a rec.
3674  *
3675  *      \param  dt      osd index object
3676  *      \param  key     key for index
3677  *      \param  rec     record reference
3678  *
3679  *      \retval  +ve  success : exact mach
3680  *      \retval  0    return record with key not greater than \a key
3681  *      \retval -ve   failure
3682  */
3683 static int osd_index_iam_lookup(const struct lu_env *env, struct dt_object *dt,
3684                                 struct dt_rec *rec, const struct dt_key *key,
3685                                 struct lustre_capa *capa)
3686 {
3687         struct osd_object      *obj = osd_dt_obj(dt);
3688         struct iam_path_descr  *ipd;
3689         struct iam_container   *bag = &obj->oo_dir->od_container;
3690         struct osd_thread_info *oti = osd_oti_get(env);
3691         struct iam_iterator    *it = &oti->oti_idx_it;
3692         struct iam_rec         *iam_rec;
3693         int                     rc;
3694
3695         ENTRY;
3696
3697         LASSERT(osd_invariant(obj));
3698         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3699         LASSERT(bag->ic_object == obj->oo_inode);
3700
3701         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
3702                 RETURN(-EACCES);
3703
3704         ipd = osd_idx_ipd_get(env, bag);
3705         if (IS_ERR(ipd))
3706                 RETURN(-ENOMEM);
3707
3708         /* got ipd now we can start iterator. */
3709         iam_it_init(it, bag, 0, ipd);
3710
3711         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3712                 /* swab quota uid/gid provided by caller */
3713                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3714                 key = (const struct dt_key *)&oti->oti_quota_id;
3715         }
3716
3717         rc = iam_it_get(it, (struct iam_key *)key);
3718         if (rc >= 0) {
3719                 if (S_ISDIR(obj->oo_inode->i_mode))
3720                         iam_rec = (struct iam_rec *)oti->oti_ldp;
3721                 else
3722                         iam_rec = (struct iam_rec *) rec;
3723
3724                 iam_reccpy(&it->ii_path.ip_leaf, (struct iam_rec *)iam_rec);
3725
3726                 if (S_ISDIR(obj->oo_inode->i_mode))
3727                         osd_fid_unpack((struct lu_fid *) rec,
3728                                        (struct osd_fid_pack *)iam_rec);
3729                 else if (fid_is_quota(lu_object_fid(&dt->do_lu)))
3730                         osd_quota_unpack(obj, rec);
3731         }
3732
3733         iam_it_put(it);
3734         iam_it_fini(it);
3735         osd_ipd_put(env, bag, ipd);
3736
3737         LINVRNT(osd_invariant(obj));
3738
3739         RETURN(rc);
3740 }
3741
3742 static int osd_index_declare_iam_insert(const struct lu_env *env,
3743                                         struct dt_object *dt,
3744                                         const struct dt_rec *rec,
3745                                         const struct dt_key *key,
3746                                         struct thandle *handle)
3747 {
3748         struct osd_thandle *oh;
3749
3750         LASSERT(handle != NULL);
3751
3752         oh = container_of0(handle, struct osd_thandle, ot_super);
3753         LASSERT(oh->ot_handle == NULL);
3754
3755         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3756                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
3757
3758         return 0;
3759 }
3760
3761 /**
3762  *      Inserts (key, value) pair in \a dt index object.
3763  *
3764  *      \param  dt      osd index object
3765  *      \param  key     key for index
3766  *      \param  rec     record reference
3767  *      \param  th      transaction handler
3768  *
3769  *      \retval  0  success
3770  *      \retval -ve failure
3771  */
3772 static int osd_index_iam_insert(const struct lu_env *env, struct dt_object *dt,
3773                                 const struct dt_rec *rec,
3774                                 const struct dt_key *key, struct thandle *th,
3775                                 struct lustre_capa *capa, int ignore_quota)
3776 {
3777         struct osd_object     *obj = osd_dt_obj(dt);
3778         struct iam_path_descr *ipd;
3779         struct osd_thandle    *oh;
3780         struct iam_container  *bag = &obj->oo_dir->od_container;
3781         struct osd_thread_info *oti = osd_oti_get(env);
3782         struct iam_rec         *iam_rec;
3783         int                     rc;
3784
3785         ENTRY;
3786
3787         LINVRNT(osd_invariant(obj));
3788         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3789         LASSERT(bag->ic_object == obj->oo_inode);
3790         LASSERT(th != NULL);
3791
3792         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
3793                 RETURN(-EACCES);
3794
3795         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3796
3797         ipd = osd_idx_ipd_get(env, bag);
3798         if (unlikely(ipd == NULL))
3799                 RETURN(-ENOMEM);
3800
3801         oh = container_of0(th, struct osd_thandle, ot_super);
3802         LASSERT(oh->ot_handle != NULL);
3803         LASSERT(oh->ot_handle->h_transaction != NULL);
3804         if (S_ISDIR(obj->oo_inode->i_mode)) {
3805                 iam_rec = (struct iam_rec *)oti->oti_ldp;
3806                 osd_fid_pack((struct osd_fid_pack *)iam_rec, rec, &oti->oti_fid);
3807         } else if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3808                 /* pack quota uid/gid */
3809                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3810                 key = (const struct dt_key *)&oti->oti_quota_id;
3811                 /* pack quota record */
3812                 rec = osd_quota_pack(obj, rec, &oti->oti_quota_rec);
3813                 iam_rec = (struct iam_rec *)rec;
3814         } else {
3815                 iam_rec = (struct iam_rec *)rec;
3816         }
3817
3818         rc = iam_insert(oh->ot_handle, bag, (const struct iam_key *)key,
3819                         iam_rec, ipd);
3820         osd_ipd_put(env, bag, ipd);
3821         LINVRNT(osd_invariant(obj));
3822         RETURN(rc);
3823 }
3824
3825 /**
3826  * Calls ldiskfs_add_entry() to add directory entry
3827  * into the directory. This is required for
3828  * interoperability mode (b11826)
3829  *
3830  * \retval   0, on success
3831  * \retval -ve, on error
3832  */
3833 static int __osd_ea_add_rec(struct osd_thread_info *info,
3834                             struct osd_object *pobj, struct inode  *cinode,
3835                             const char *name, const struct dt_rec *fid,
3836                             struct htree_lock *hlock, struct thandle *th)
3837 {
3838         struct ldiskfs_dentry_param *ldp;
3839         struct dentry               *child;
3840         struct osd_thandle          *oth;
3841         int                          rc;
3842
3843         oth = container_of(th, struct osd_thandle, ot_super);
3844         LASSERT(oth->ot_handle != NULL);
3845         LASSERT(oth->ot_handle->h_transaction != NULL);
3846         LASSERT(pobj->oo_inode);
3847
3848         ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
3849         if (unlikely(pobj->oo_inode ==
3850                      osd_sb(osd_obj2dev(pobj))->s_root->d_inode))
3851                 ldp->edp_magic = 0;
3852         else
3853                 osd_get_ldiskfs_dirent_param(ldp, fid);
3854         child = osd_child_dentry_get(info->oti_env, pobj, name, strlen(name));
3855         child->d_fsdata = (void *)ldp;
3856         ll_vfs_dq_init(pobj->oo_inode);
3857         rc = osd_ldiskfs_add_entry(oth->ot_handle, child, cinode, hlock);
3858
3859         RETURN(rc);
3860 }
3861
3862 /**
3863  * Calls ldiskfs_add_dot_dotdot() to add dot and dotdot entries
3864  * into the directory.Also sets flags into osd object to
3865  * indicate dot and dotdot are created. This is required for
3866  * interoperability mode (b11826)
3867  *
3868  * \param dir   directory for dot and dotdot fixup.
3869  * \param obj   child object for linking
3870  *
3871  * \retval   0, on success
3872  * \retval -ve, on error
3873  */
3874 static int osd_add_dot_dotdot(struct osd_thread_info *info,
3875                               struct osd_object *dir,
3876                               struct inode  *parent_dir, const char *name,
3877                               const struct dt_rec *dot_fid,
3878                               const struct dt_rec *dot_dot_fid,
3879                               struct thandle *th)
3880 {
3881         struct inode                *inode = dir->oo_inode;
3882         struct osd_thandle          *oth;
3883         int result = 0;
3884
3885         oth = container_of(th, struct osd_thandle, ot_super);
3886         LASSERT(oth->ot_handle->h_transaction != NULL);
3887         LASSERT(S_ISDIR(dir->oo_inode->i_mode));
3888
3889         if (strcmp(name, dot) == 0) {
3890                 if (dir->oo_compat_dot_created) {
3891                         result = -EEXIST;
3892                 } else {
3893                         LASSERT(inode == parent_dir);
3894                         dir->oo_compat_dot_created = 1;
3895                         result = 0;
3896                 }
3897         } else if (strcmp(name, dotdot) == 0) {
3898                 if (!dir->oo_compat_dot_created)
3899                         return -EINVAL;
3900                 /* in case of rename, dotdot is already created */
3901                 if (dir->oo_compat_dotdot_created) {
3902                         return __osd_ea_add_rec(info, dir, parent_dir, name,
3903                                                 dot_dot_fid, NULL, th);
3904                 }
3905
3906                 result = osd_add_dot_dotdot_internal(info, dir->oo_inode,
3907                                                 parent_dir, dot_fid,
3908                                                 dot_dot_fid, oth);
3909                 if (result == 0)
3910                         dir->oo_compat_dotdot_created = 1;
3911         }
3912
3913         return result;
3914 }
3915
3916
3917 /**
3918  * It will call the appropriate osd_add* function and return the
3919  * value, return by respective functions.
3920  */
3921 static int osd_ea_add_rec(const struct lu_env *env, struct osd_object *pobj,
3922                           struct inode *cinode, const char *name,
3923                           const struct dt_rec *fid, struct thandle *th)
3924 {
3925         struct osd_thread_info *info   = osd_oti_get(env);
3926         struct htree_lock      *hlock;
3927         int                     rc;
3928
3929         hlock = pobj->oo_hl_head != NULL ? info->oti_hlock : NULL;
3930
3931         if (name[0] == '.' && (name[1] == '\0' || (name[1] == '.' &&
3932                                                    name[2] =='\0'))) {
3933                 if (hlock != NULL) {
3934                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
3935                                            pobj->oo_inode, 0);
3936                 } else {
3937                         down_write(&pobj->oo_ext_idx_sem);
3938                 }
3939                 rc = osd_add_dot_dotdot(info, pobj, cinode, name,
3940                      (struct dt_rec *)lu_object_fid(&pobj->oo_dt.do_lu),
3941                                         fid, th);
3942         } else {
3943                 if (hlock != NULL) {
3944                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
3945                                            pobj->oo_inode, LDISKFS_HLOCK_ADD);
3946                 } else {
3947                         down_write(&pobj->oo_ext_idx_sem);
3948                 }
3949
3950                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_INDIR)) {
3951                         struct lu_fid *tfid = &info->oti_fid;
3952
3953                         *tfid = *(const struct lu_fid *)fid;
3954                         tfid->f_ver = ~0;
3955                         rc = __osd_ea_add_rec(info, pobj, cinode, name,
3956                                               (const struct dt_rec *)tfid,
3957                                               hlock, th);
3958                 } else {
3959                         rc = __osd_ea_add_rec(info, pobj, cinode, name, fid,
3960                                               hlock, th);
3961                 }
3962         }
3963         if (hlock != NULL)
3964                 ldiskfs_htree_unlock(hlock);
3965         else
3966                 up_write(&pobj->oo_ext_idx_sem);
3967
3968         return rc;
3969 }
3970
3971 static void
3972 osd_consistency_check(struct osd_thread_info *oti, struct osd_device *dev,
3973                       struct osd_idmap_cache *oic)
3974 {
3975         struct osd_scrub    *scrub = &dev->od_scrub;
3976         struct lu_fid       *fid   = &oic->oic_fid;
3977         struct osd_inode_id *id    = &oti->oti_id;
3978         int                  once  = 0;
3979         int                  rc;
3980         ENTRY;
3981
3982         if (!fid_is_norm(fid) && !fid_is_igif(fid))
3983                 RETURN_EXIT;
3984
3985 again:
3986         rc = osd_oi_lookup(oti, dev, fid, id, OI_CHECK_FLD);
3987         if (rc != 0 && rc != -ENOENT)
3988                 RETURN_EXIT;
3989
3990         if (rc == 0 && osd_id_eq(id, &oic->oic_lid))
3991                 RETURN_EXIT;
3992
3993         if (thread_is_running(&scrub->os_thread)) {
3994                 rc = osd_oii_insert(dev, oic, rc == -ENOENT);
3995                 /* There is race condition between osd_oi_lookup and OI scrub.
3996                  * The OI scrub finished just after osd_oi_lookup() failure.
3997                  * Under such case, it is unnecessary to trigger OI scrub again,
3998                  * but try to call osd_oi_lookup() again. */
3999                 if (unlikely(rc == -EAGAIN))
4000                         goto again;
4001
4002                 RETURN_EXIT;
4003         }
4004
4005         if (!dev->od_noscrub && ++once == 1) {
4006                 rc = osd_scrub_start(dev);
4007                 LCONSOLE_WARN("%.16s: trigger OI scrub by RPC for "DFID
4008                               ", rc = %d [2]\n",
4009                               LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name,
4010                               PFID(fid), rc);
4011                 if (rc == 0)
4012                         goto again;
4013         }
4014
4015         EXIT;
4016 }
4017
4018 static int osd_fail_fid_lookup(struct osd_thread_info *oti,
4019                                struct osd_device *dev,
4020                                struct osd_idmap_cache *oic,
4021                                struct lu_fid *fid, __u32 ino)
4022 {
4023         struct lustre_mdt_attrs *lma   = &oti->oti_mdt_attrs;
4024         struct inode            *inode;
4025         int                      rc;
4026
4027         osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
4028         inode = osd_iget(oti, dev, &oic->oic_lid);
4029         if (IS_ERR(inode)) {
4030                 fid_zero(&oic->oic_fid);
4031                 return PTR_ERR(inode);
4032         }
4033
4034         rc = osd_get_lma(oti, inode, &oti->oti_obj_dentry, lma);
4035         iput(inode);
4036         if (rc != 0)
4037                 fid_zero(&oic->oic_fid);
4038         else
4039                 *fid = oic->oic_fid = lma->lma_self_fid;
4040         return rc;
4041 }
4042
4043 int osd_add_oi_cache(struct osd_thread_info *info, struct osd_device *osd,
4044                      struct osd_inode_id *id, const struct lu_fid *fid)
4045 {
4046         CDEBUG(D_INODE, "add "DFID" %u:%u to info %p\n", PFID(fid),
4047                id->oii_ino, id->oii_gen, info);
4048         info->oti_cache.oic_lid = *id;
4049         info->oti_cache.oic_fid = *fid;
4050         info->oti_cache.oic_dev = osd;
4051
4052         return 0;
4053 }
4054
4055 /**
4056  * Calls ->lookup() to find dentry. From dentry get inode and
4057  * read inode's ea to get fid. This is required for  interoperability
4058  * mode (b11826)
4059  *
4060  * \retval   0, on success
4061  * \retval -ve, on error
4062  */
4063 static int osd_ea_lookup_rec(const struct lu_env *env, struct osd_object *obj,
4064                              struct dt_rec *rec, const struct dt_key *key)
4065 {
4066         struct inode               *dir    = obj->oo_inode;
4067         struct dentry              *dentry;
4068         struct ldiskfs_dir_entry_2 *de;
4069         struct buffer_head         *bh;
4070         struct lu_fid              *fid = (struct lu_fid *) rec;
4071         struct htree_lock          *hlock = NULL;
4072         int                         ino;
4073         int                         rc;
4074         ENTRY;
4075
4076         LASSERT(dir->i_op != NULL && dir->i_op->lookup != NULL);
4077
4078         dentry = osd_child_dentry_get(env, obj,
4079                                       (char *)key, strlen((char *)key));
4080
4081         if (obj->oo_hl_head != NULL) {
4082                 hlock = osd_oti_get(env)->oti_hlock;
4083                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
4084                                    dir, LDISKFS_HLOCK_LOOKUP);
4085         } else {
4086                 down_read(&obj->oo_ext_idx_sem);
4087         }
4088
4089         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
4090         if (bh) {
4091                 struct osd_thread_info *oti = osd_oti_get(env);
4092                 struct osd_inode_id *id = &oti->oti_id;
4093                 struct osd_idmap_cache *oic = &oti->oti_cache;
4094                 struct osd_device *dev = osd_obj2dev(obj);
4095                 struct osd_scrub *scrub = &dev->od_scrub;
4096                 struct scrub_file *sf = &scrub->os_file;
4097
4098                 ino = le32_to_cpu(de->inode);
4099                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP)) {
4100                         brelse(bh);
4101                         rc = osd_fail_fid_lookup(oti, dev, oic, fid, ino);
4102                         GOTO(out, rc);
4103                 }
4104
4105                 rc = osd_get_fid_from_dentry(de, rec);
4106
4107                 /* done with de, release bh */
4108                 brelse(bh);
4109                 if (rc != 0)
4110                         rc = osd_ea_fid_get(env, obj, ino, fid, id);
4111                 else
4112                         osd_id_gen(id, ino, OSD_OII_NOGEN);
4113                 if (rc != 0) {
4114                         fid_zero(&oic->oic_fid);
4115                         GOTO(out, rc);
4116                 }
4117
4118                 if (osd_remote_fid(env, dev, fid))
4119                         GOTO(out, rc = 0);
4120
4121                 rc = osd_add_oi_cache(osd_oti_get(env), osd_obj2dev(obj), id,
4122                                       fid);
4123                 if (rc != 0)
4124                         GOTO(out, rc);
4125                 if ((scrub->os_pos_current <= ino) &&
4126                     ((sf->sf_flags & SF_INCONSISTENT) ||
4127                      (sf->sf_flags & SF_UPGRADE && fid_is_igif(fid)) ||
4128                      ldiskfs_test_bit(osd_oi_fid2idx(dev, fid),
4129                                       sf->sf_oi_bitmap)))
4130                         osd_consistency_check(oti, dev, oic);
4131         } else {
4132                 rc = -ENOENT;
4133         }
4134
4135         GOTO(out, rc);
4136
4137 out:
4138         if (hlock != NULL)
4139                 ldiskfs_htree_unlock(hlock);
4140         else
4141                 up_read(&obj->oo_ext_idx_sem);
4142         return rc;
4143 }
4144
4145 /**
4146  * Find the osd object for given fid.
4147  *
4148  * \param fid need to find the osd object having this fid
4149  *
4150  * \retval osd_object on success
4151  * \retval        -ve on error
4152  */
4153 struct osd_object *osd_object_find(const struct lu_env *env,
4154                                    struct dt_object *dt,
4155                                    const struct lu_fid *fid)
4156 {
4157         struct lu_device  *ludev = dt->do_lu.lo_dev;
4158         struct osd_object *child = NULL;
4159         struct lu_object  *luch;
4160         struct lu_object  *lo;
4161
4162         /*
4163          * at this point topdev might not exist yet
4164          * (i.e. MGS is preparing profiles). so we can
4165          * not rely on topdev and instead lookup with
4166          * our device passed as topdev. this can't work
4167          * if the object isn't cached yet (as osd doesn't
4168          * allocate lu_header). IOW, the object must be
4169          * in the cache, otherwise lu_object_alloc() crashes
4170          * -bzzz
4171          */
4172         luch = lu_object_find_at(env, ludev, fid, NULL);
4173         if (!IS_ERR(luch)) {
4174                 if (lu_object_exists(luch)) {
4175                         lo = lu_object_locate(luch->lo_header, ludev->ld_type);
4176                         if (lo != NULL)
4177                                 child = osd_obj(lo);
4178                         else
4179                                 LU_OBJECT_DEBUG(D_ERROR, env, luch,
4180                                                 "lu_object can't be located"
4181                                                 DFID"\n", PFID(fid));
4182
4183                         if (child == NULL) {
4184                                 lu_object_put(env, luch);
4185                                 CERROR("Unable to get osd_object\n");
4186                                 child = ERR_PTR(-ENOENT);
4187                         }
4188                 } else {
4189                         LU_OBJECT_DEBUG(D_ERROR, env, luch,
4190                                         "lu_object does not exists "DFID"\n",
4191                                         PFID(fid));
4192                         lu_object_put(env, luch);
4193                         child = ERR_PTR(-ENOENT);
4194                 }
4195         } else {
4196                 child = ERR_CAST(luch);
4197         }
4198
4199         return child;
4200 }
4201
4202 /**
4203  * Put the osd object once done with it.
4204  *
4205  * \param obj osd object that needs to be put
4206  */
4207 static inline void osd_object_put(const struct lu_env *env,
4208                                   struct osd_object *obj)
4209 {
4210         lu_object_put(env, &obj->oo_dt.do_lu);
4211 }
4212
4213 static int osd_index_declare_ea_insert(const struct lu_env *env,
4214                                        struct dt_object *dt,
4215                                        const struct dt_rec *rec,
4216                                        const struct dt_key *key,
4217                                        struct thandle *handle)
4218 {
4219         struct osd_thandle      *oh;
4220         struct osd_device       *osd   = osd_dev(dt->do_lu.lo_dev);
4221         struct lu_fid           *fid = (struct lu_fid *)rec;
4222         int                     rc;
4223         ENTRY;
4224
4225         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
4226         LASSERT(handle != NULL);
4227
4228         oh = container_of0(handle, struct osd_thandle, ot_super);
4229         LASSERT(oh->ot_handle == NULL);
4230
4231         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4232                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
4233
4234         if (osd_dt_obj(dt)->oo_inode == NULL) {
4235                 const char *name  = (const char *)key;
4236                 /* Object is not being created yet. Only happens when
4237                  *     1. declare directory create
4238                  *     2. declare insert .
4239                  *     3. declare insert ..
4240                  */
4241                 LASSERT(strcmp(name, dotdot) == 0 || strcmp(name, dot) == 0);
4242         } else {
4243                 struct inode *inode = osd_dt_obj(dt)->oo_inode;
4244
4245                 /* We ignore block quota on meta pool (MDTs), so needn't
4246                  * calculate how many blocks will be consumed by this index
4247                  * insert */
4248                 rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0,
4249                                            oh, true, true, NULL, false);
4250         }
4251
4252         if (fid == NULL)
4253                 RETURN(0);
4254
4255         rc = osd_remote_fid(env, osd, fid);
4256         if (rc <= 0)
4257                 RETURN(rc);
4258
4259         rc = 0;
4260
4261         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
4262                              osd_dto_credits_noquota[DTO_OBJECT_CREATE]);
4263         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4264                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
4265         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4266                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
4267
4268         RETURN(rc);
4269 }
4270
4271 /**
4272  * Index add function for interoperability mode (b11826).
4273  * It will add the directory entry.This entry is needed to
4274  * maintain name->fid mapping.
4275  *
4276  * \param key it is key i.e. file entry to be inserted
4277  * \param rec it is value of given key i.e. fid
4278  *
4279  * \retval   0, on success
4280  * \retval -ve, on error
4281  */
4282 static int osd_index_ea_insert(const struct lu_env *env, struct dt_object *dt,
4283                                const struct dt_rec *rec,
4284                                const struct dt_key *key, struct thandle *th,
4285                                struct lustre_capa *capa, int ignore_quota)
4286 {
4287         struct osd_object       *obj = osd_dt_obj(dt);
4288         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
4289         struct lu_fid           *fid = (struct lu_fid *) rec;
4290         const char              *name = (const char *)key;
4291         struct osd_thread_info  *oti   = osd_oti_get(env);
4292         struct osd_inode_id     *id    = &oti->oti_id;
4293         struct inode            *child_inode = NULL;
4294         struct osd_object       *child = NULL;
4295         int                     rc;
4296         ENTRY;
4297
4298         LASSERT(osd_invariant(obj));
4299         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
4300         LASSERT(th != NULL);
4301
4302         osd_trans_exec_op(env, th, OSD_OT_INSERT);
4303
4304         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
4305                 RETURN(-EACCES);
4306
4307         LASSERTF(fid_is_sane(fid), "fid"DFID" is insane!", PFID(fid));
4308
4309         rc = osd_remote_fid(env, osd, fid);
4310         if (rc < 0) {
4311                 CERROR("%s: Can not find object "DFID" rc %d\n",
4312                        osd_name(osd), PFID(fid), rc);
4313                 RETURN(rc);
4314         }
4315
4316         if (rc == 1) {
4317                 /* Insert remote entry */
4318                 if (strcmp(name, dotdot) == 0 && strlen(name) == 2) {
4319                         struct osd_mdobj_map    *omm = osd->od_mdt_map;
4320                         struct osd_thandle      *oh;
4321
4322                         /* If parent on remote MDT, we need put this object
4323                          * under AGENT */
4324                         oh = container_of(th, typeof(*oh), ot_super);
4325                         rc = osd_add_to_remote_parent(env, osd, obj, oh);
4326                         if (rc != 0) {
4327                                 CERROR("%s: add "DFID" error: rc = %d\n",
4328                                        osd_name(osd),
4329                                        PFID(lu_object_fid(&dt->do_lu)), rc);
4330                                 RETURN(rc);
4331                         }
4332
4333                         child_inode = igrab(omm->omm_remote_parent->d_inode);
4334                 } else {
4335                         child_inode = osd_create_local_agent_inode(env, osd,
4336                                                                    obj, fid,
4337                                                                    th);
4338                         if (IS_ERR(child_inode))
4339                                 RETURN(PTR_ERR(child_inode));
4340                 }
4341         } else {
4342                 /* Insert local entry */
4343                 child = osd_object_find(env, dt, fid);
4344                 if (IS_ERR(child)) {
4345                         CERROR("%s: Can not find object "DFID"%u:%u: rc = %d\n",
4346                                osd_name(osd), PFID(fid),
4347                                id->oii_ino, id->oii_gen,
4348                                (int)PTR_ERR(child));
4349                         RETURN(PTR_ERR(child));
4350                 }
4351                 child_inode = igrab(child->oo_inode);
4352         }
4353
4354         rc = osd_ea_add_rec(env, obj, child_inode, name, rec, th);
4355
4356         iput(child_inode);
4357         if (child != NULL)
4358                 osd_object_put(env, child);
4359         LASSERT(osd_invariant(obj));
4360         RETURN(rc);
4361 }
4362
4363 /**
4364  *  Initialize osd Iterator for given osd index object.
4365  *
4366  *  \param  dt      osd index object
4367  */
4368
4369 static struct dt_it *osd_it_iam_init(const struct lu_env *env,
4370                                      struct dt_object *dt,
4371                                      __u32 unused,
4372                                      struct lustre_capa *capa)
4373 {
4374         struct osd_it_iam      *it;
4375         struct osd_thread_info *oti = osd_oti_get(env);
4376         struct osd_object      *obj = osd_dt_obj(dt);
4377         struct lu_object       *lo  = &dt->do_lu;
4378         struct iam_path_descr  *ipd;
4379         struct iam_container   *bag = &obj->oo_dir->od_container;
4380
4381         LASSERT(lu_object_exists(lo));
4382
4383         if (osd_object_auth(env, dt, capa, CAPA_OPC_BODY_READ))
4384                 return ERR_PTR(-EACCES);
4385
4386         it = &oti->oti_it;
4387         ipd = osd_it_ipd_get(env, bag);
4388         if (likely(ipd != NULL)) {
4389                 it->oi_obj = obj;
4390                 it->oi_ipd = ipd;
4391                 lu_object_get(lo);
4392                 iam_it_init(&it->oi_it, bag, IAM_IT_MOVE, ipd);
4393                 return (struct dt_it *)it;
4394         }
4395         return ERR_PTR(-ENOMEM);
4396 }
4397
4398 /**
4399  * free given Iterator.
4400  */
4401
4402 static void osd_it_iam_fini(const struct lu_env *env, struct dt_it *di)
4403 {
4404         struct osd_it_iam *it = (struct osd_it_iam *)di;
4405         struct osd_object *obj = it->oi_obj;
4406
4407         iam_it_fini(&it->oi_it);
4408         osd_ipd_put(env, &obj->oo_dir->od_container, it->oi_ipd);
4409         lu_object_put(env, &obj->oo_dt.do_lu);
4410 }
4411
4412 /**
4413  *  Move Iterator to record specified by \a key
4414  *
4415  *  \param  di      osd iterator
4416  *  \param  key     key for index
4417  *
4418  *  \retval +ve  di points to record with least key not larger than key
4419  *  \retval  0   di points to exact matched key
4420  *  \retval -ve  failure
4421  */
4422
4423 static int osd_it_iam_get(const struct lu_env *env,
4424                           struct dt_it *di, const struct dt_key *key)
4425 {
4426         struct osd_thread_info  *oti = osd_oti_get(env);
4427         struct osd_it_iam       *it = (struct osd_it_iam *)di;
4428
4429         if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
4430                 /* swab quota uid/gid */
4431                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
4432                 key = (struct dt_key *)&oti->oti_quota_id;
4433         }
4434
4435         return iam_it_get(&it->oi_it, (const struct iam_key *)key);
4436 }
4437
4438 /**
4439  *  Release Iterator
4440  *
4441  *  \param  di      osd iterator
4442  */
4443 static void osd_it_iam_put(const struct lu_env *env, struct dt_it *di)
4444 {
4445         struct osd_it_iam *it = (struct osd_it_iam *)di;
4446
4447         iam_it_put(&it->oi_it);
4448 }
4449
4450 /**
4451  *  Move iterator by one record
4452  *
4453  *  \param  di      osd iterator
4454  *
4455  *  \retval +1   end of container reached
4456  *  \retval  0   success
4457  *  \retval -ve  failure
4458  */
4459
4460 static int osd_it_iam_next(const struct lu_env *env, struct dt_it *di)
4461 {
4462         struct osd_it_iam *it = (struct osd_it_iam *)di;
4463
4464         return iam_it_next(&it->oi_it);
4465 }
4466
4467 /**
4468  * Return pointer to the key under iterator.
4469  */
4470
4471 static struct dt_key *osd_it_iam_key(const struct lu_env *env,
4472                                  const struct dt_it *di)
4473 {
4474         struct osd_thread_info *oti = osd_oti_get(env);
4475         struct osd_it_iam      *it = (struct osd_it_iam *)di;
4476         struct osd_object      *obj = it->oi_obj;
4477         struct dt_key          *key;
4478
4479         key = (struct dt_key *)iam_it_key_get(&it->oi_it);
4480
4481         if (!IS_ERR(key) && fid_is_quota(lu_object_fid(&obj->oo_dt.do_lu))) {
4482                 /* swab quota uid/gid */
4483                 oti->oti_quota_id = le64_to_cpu(*((__u64 *)key));
4484                 key = (struct dt_key *)&oti->oti_quota_id;
4485         }
4486
4487         return key;
4488 }
4489
4490 /**
4491  * Return size of key under iterator (in bytes)
4492  */
4493
4494 static int osd_it_iam_key_size(const struct lu_env *env, const struct dt_it *di)
4495 {
4496         struct osd_it_iam *it = (struct osd_it_iam *)di;
4497
4498         return iam_it_key_size(&it->oi_it);
4499 }
4500
4501 static inline void
4502 osd_it_append_attrs(struct lu_dirent *ent, int len, __u16 type)
4503 {
4504         /* check if file type is required */
4505         if (ent->lde_attrs & LUDA_TYPE) {
4506                 struct luda_type *lt;
4507                 int align = sizeof(*lt) - 1;
4508
4509                 len = (len + align) & ~align;
4510                 lt = (struct luda_type *)(ent->lde_name + len);
4511                 lt->lt_type = cpu_to_le16(DTTOIF(type));
4512         }
4513
4514         ent->lde_attrs = cpu_to_le32(ent->lde_attrs);
4515 }
4516
4517 /**
4518  * build lu direct from backend fs dirent.
4519  */
4520
4521 static inline void
4522 osd_it_pack_dirent(struct lu_dirent *ent, struct lu_fid *fid, __u64 offset,
4523                    char *name, __u16 namelen, __u16 type, __u32 attr)
4524 {
4525         ent->lde_attrs = attr | LUDA_FID;
4526         fid_cpu_to_le(&ent->lde_fid, fid);
4527
4528         ent->lde_hash = cpu_to_le64(offset);
4529         ent->lde_reclen = cpu_to_le16(lu_dirent_calc_size(namelen, attr));
4530
4531         strncpy(ent->lde_name, name, namelen);
4532         ent->lde_name[namelen] = '\0';
4533         ent->lde_namelen = cpu_to_le16(namelen);
4534
4535         /* append lustre attributes */
4536         osd_it_append_attrs(ent, namelen, type);
4537 }
4538
4539 /**
4540  * Return pointer to the record under iterator.
4541  */
4542 static int osd_it_iam_rec(const struct lu_env *env,
4543                           const struct dt_it *di,
4544                           struct dt_rec *dtrec, __u32 attr)
4545 {
4546         struct osd_it_iam      *it   = (struct osd_it_iam *)di;
4547         struct osd_thread_info *info = osd_oti_get(env);
4548         ENTRY;
4549
4550         if (S_ISDIR(it->oi_obj->oo_inode->i_mode)) {
4551                 const struct osd_fid_pack *rec;
4552                 struct lu_fid             *fid = &info->oti_fid;
4553                 struct lu_dirent          *lde = (struct lu_dirent *)dtrec;
4554                 char                      *name;
4555                 int                        namelen;
4556                 __u64                      hash;
4557                 int                        rc;
4558
4559                 name = (char *)iam_it_key_get(&it->oi_it);
4560                 if (IS_ERR(name))
4561                         RETURN(PTR_ERR(name));
4562
4563                 namelen = iam_it_key_size(&it->oi_it);
4564
4565                 rec = (const struct osd_fid_pack *)iam_it_rec_get(&it->oi_it);
4566                 if (IS_ERR(rec))
4567                         RETURN(PTR_ERR(rec));
4568
4569                 rc = osd_fid_unpack(fid, rec);
4570                 if (rc)
4571                         RETURN(rc);
4572
4573                 hash = iam_it_store(&it->oi_it);
4574
4575                 /* IAM does not store object type in IAM index (dir) */
4576                 osd_it_pack_dirent(lde, fid, hash, name, namelen,
4577                                    0, LUDA_FID);
4578         } else if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
4579                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
4580                            (struct iam_rec *)dtrec);
4581                 osd_quota_unpack(it->oi_obj, dtrec);
4582         } else {
4583                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
4584                            (struct iam_rec *)dtrec);
4585         }
4586
4587         RETURN(0);
4588 }
4589
4590 /**
4591  * Returns cookie for current Iterator position.
4592  */
4593 static __u64 osd_it_iam_store(const struct lu_env *env, const struct dt_it *di)
4594 {
4595         struct osd_it_iam *it = (struct osd_it_iam *)di;
4596
4597         return iam_it_store(&it->oi_it);
4598 }
4599
4600 /**
4601  * Restore iterator from cookie.
4602  *
4603  * \param  di      osd iterator
4604  * \param  hash    Iterator location cookie
4605  *
4606  * \retval +ve  di points to record with least key not larger than key.
4607  * \retval  0   di points to exact matched key
4608  * \retval -ve  failure
4609  */
4610
4611 static int osd_it_iam_load(const struct lu_env *env,
4612                            const struct dt_it *di, __u64 hash)
4613 {
4614         struct osd_it_iam *it = (struct osd_it_iam *)di;
4615
4616         return iam_it_load(&it->oi_it, hash);
4617 }
4618
4619 static const struct dt_index_operations osd_index_iam_ops = {
4620         .dio_lookup         = osd_index_iam_lookup,
4621         .dio_declare_insert = osd_index_declare_iam_insert,
4622         .dio_insert         = osd_index_iam_insert,
4623         .dio_declare_delete = osd_index_declare_iam_delete,
4624         .dio_delete         = osd_index_iam_delete,
4625         .dio_it     = {
4626                 .init     = osd_it_iam_init,
4627                 .fini     = osd_it_iam_fini,
4628                 .get      = osd_it_iam_get,
4629                 .put      = osd_it_iam_put,
4630                 .next     = osd_it_iam_next,
4631                 .key      = osd_it_iam_key,
4632                 .key_size = osd_it_iam_key_size,
4633                 .rec      = osd_it_iam_rec,
4634                 .store    = osd_it_iam_store,
4635                 .load     = osd_it_iam_load
4636         }
4637 };
4638
4639
4640 /**
4641  * Creates or initializes iterator context.
4642  *
4643  * \retval struct osd_it_ea, iterator structure on success
4644  *
4645  */
4646 static struct dt_it *osd_it_ea_init(const struct lu_env *env,
4647                                     struct dt_object *dt,
4648                                     __u32 attr,
4649                                     struct lustre_capa *capa)
4650 {
4651         struct osd_object       *obj  = osd_dt_obj(dt);
4652         struct osd_thread_info  *info = osd_oti_get(env);
4653         struct osd_it_ea        *it   = &info->oti_it_ea;
4654         struct file             *file = &it->oie_file;
4655         struct lu_object        *lo   = &dt->do_lu;
4656         struct dentry           *obj_dentry = &info->oti_it_dentry;
4657         ENTRY;
4658         LASSERT(lu_object_exists(lo));
4659
4660         obj_dentry->d_inode = obj->oo_inode;
4661         obj_dentry->d_sb = osd_sb(osd_obj2dev(obj));
4662         obj_dentry->d_name.hash = 0;
4663
4664         it->oie_rd_dirent       = 0;
4665         it->oie_it_dirent       = 0;
4666         it->oie_dirent          = NULL;
4667         it->oie_buf             = info->oti_it_ea_buf;
4668         it->oie_obj             = obj;
4669
4670         /* Reset the "file" totally to avoid to reuse any old value from
4671          * former readdir handling, the "file->f_pos" should be zero. */
4672         memset(file, 0, sizeof(*file));
4673         /* Only FMODE_64BITHASH or FMODE_32BITHASH should be set, NOT both. */
4674         if (attr & LUDA_64BITHASH)
4675                 file->f_mode    = FMODE_64BITHASH;
4676         else
4677                 file->f_mode    = FMODE_32BITHASH;
4678         file->f_dentry          = obj_dentry;
4679         file->f_mapping         = obj->oo_inode->i_mapping;
4680         file->f_op              = obj->oo_inode->i_fop;
4681         set_file_inode(file, obj->oo_inode);
4682
4683         lu_object_get(lo);
4684         RETURN((struct dt_it *) it);
4685 }
4686
4687 /**
4688  * Destroy or finishes iterator context.
4689  *
4690  * \param di iterator structure to be destroyed
4691  */
4692 static void osd_it_ea_fini(const struct lu_env *env, struct dt_it *di)
4693 {
4694         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
4695         struct osd_object    *obj  = it->oie_obj;
4696         struct inode       *inode  = obj->oo_inode;
4697
4698         ENTRY;
4699         it->oie_file.f_op->release(inode, &it->oie_file);
4700         lu_object_put(env, &obj->oo_dt.do_lu);
4701         EXIT;
4702 }
4703
4704 /**
4705  * It position the iterator at given key, so that next lookup continues from
4706  * that key Or it is similar to dio_it->load() but based on a key,
4707  * rather than file position.
4708  *
4709  * As a special convention, osd_it_ea_get(env, di, "") has to rewind iterator
4710  * to the beginning.
4711  *
4712  * TODO: Presently return +1 considering it is only used by mdd_dir_is_empty().
4713  */
4714 static int osd_it_ea_get(const struct lu_env *env,
4715                          struct dt_it *di, const struct dt_key *key)
4716 {
4717         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
4718
4719         ENTRY;
4720         LASSERT(((const char *)key)[0] == '\0');
4721         it->oie_file.f_pos      = 0;
4722         it->oie_rd_dirent       = 0;
4723         it->oie_it_dirent       = 0;
4724         it->oie_dirent          = NULL;
4725
4726         RETURN(+1);
4727 }
4728
4729 /**
4730  * Does nothing
4731  */
4732 static void osd_it_ea_put(const struct lu_env *env, struct dt_it *di)
4733 {
4734 }
4735
4736 /**
4737  * It is called internally by ->readdir(). It fills the
4738  * iterator's in-memory data structure with required
4739  * information i.e. name, namelen, rec_size etc.
4740  *
4741  * \param buf in which information to be filled in.
4742  * \param name name of the file in given dir
4743  *
4744  * \retval 0 on success
4745  * \retval 1 on buffer full
4746  */
4747 static int osd_ldiskfs_filldir(char *buf, const char *name, int namelen,
4748                                loff_t offset, __u64 ino,
4749                                unsigned d_type)
4750 {
4751         struct osd_it_ea        *it   = (struct osd_it_ea *)buf;
4752         struct osd_object       *obj  = it->oie_obj;
4753         struct osd_it_ea_dirent *ent  = it->oie_dirent;
4754         struct lu_fid           *fid  = &ent->oied_fid;
4755         struct osd_fid_pack     *rec;
4756         ENTRY;
4757
4758         /* this should never happen */
4759         if (unlikely(namelen == 0 || namelen > LDISKFS_NAME_LEN)) {
4760                 CERROR("ldiskfs return invalid namelen %d\n", namelen);
4761                 RETURN(-EIO);
4762         }
4763
4764         if ((void *) ent - it->oie_buf + sizeof(*ent) + namelen >
4765             OSD_IT_EA_BUFSIZE)
4766                 RETURN(1);
4767
4768         /* "." is just the object itself. */
4769         if (namelen == 1 && name[0] == '.') {
4770                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
4771         } else if (d_type & LDISKFS_DIRENT_LUFID) {
4772                 rec = (struct osd_fid_pack*) (name + namelen + 1);
4773                 if (osd_fid_unpack(fid, rec) != 0)
4774                         fid_zero(fid);
4775         } else {
4776                 fid_zero(fid);
4777         }
4778         d_type &= ~LDISKFS_DIRENT_LUFID;
4779
4780         /* NOT export local root. */
4781         if (unlikely(osd_sb(osd_obj2dev(obj))->s_root->d_inode->i_ino == ino)) {
4782                 ino = obj->oo_inode->i_ino;
4783                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
4784         }
4785
4786         ent->oied_ino     = ino;
4787         ent->oied_off     = offset;
4788         ent->oied_namelen = namelen;
4789         ent->oied_type    = d_type;
4790
4791         memcpy(ent->oied_name, name, namelen);
4792
4793         it->oie_rd_dirent++;
4794         it->oie_dirent = (void *) ent + cfs_size_round(sizeof(*ent) + namelen);
4795         RETURN(0);
4796 }
4797
4798 /**
4799  * Calls ->readdir() to load a directory entry at a time
4800  * and stored it in iterator's in-memory data structure.
4801  *
4802  * \param di iterator's in memory structure
4803  *
4804  * \retval   0 on success
4805  * \retval -ve on error
4806  */
4807 static int osd_ldiskfs_it_fill(const struct lu_env *env,
4808                                const struct dt_it *di)
4809 {
4810         struct osd_it_ea   *it    = (struct osd_it_ea *)di;
4811         struct osd_object  *obj   = it->oie_obj;
4812         struct inode       *inode = obj->oo_inode;
4813         struct htree_lock  *hlock = NULL;
4814         int                 result = 0;
4815
4816         ENTRY;
4817         it->oie_dirent = it->oie_buf;
4818         it->oie_rd_dirent = 0;
4819
4820         if (obj->oo_hl_head != NULL) {
4821                 hlock = osd_oti_get(env)->oti_hlock;
4822                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
4823                                    inode, LDISKFS_HLOCK_READDIR);
4824         } else {
4825                 down_read(&obj->oo_ext_idx_sem);
4826         }
4827
4828         result = inode->i_fop->readdir(&it->oie_file, it,
4829                                        (filldir_t) osd_ldiskfs_filldir);
4830
4831         if (hlock != NULL)
4832                 ldiskfs_htree_unlock(hlock);
4833         else
4834                 up_read(&obj->oo_ext_idx_sem);
4835
4836         if (it->oie_rd_dirent == 0) {
4837                 result = -EIO;
4838         } else {
4839                 it->oie_dirent = it->oie_buf;
4840                 it->oie_it_dirent = 1;
4841         }
4842
4843         RETURN(result);
4844 }
4845
4846 /**
4847  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
4848  * to load a directory entry at a time and stored it in
4849  * iterator's in-memory data structure.
4850  *
4851  * \param di iterator's in memory structure
4852  *
4853  * \retval +ve iterator reached to end
4854  * \retval   0 iterator not reached to end
4855  * \retval -ve on error
4856  */
4857 static int osd_it_ea_next(const struct lu_env *env, struct dt_it *di)
4858 {
4859         struct osd_it_ea *it = (struct osd_it_ea *)di;
4860         int rc;
4861
4862         ENTRY;
4863
4864         if (it->oie_it_dirent < it->oie_rd_dirent) {
4865                 it->oie_dirent =
4866                         (void *) it->oie_dirent +
4867                         cfs_size_round(sizeof(struct osd_it_ea_dirent) +
4868                                        it->oie_dirent->oied_namelen);
4869                 it->oie_it_dirent++;
4870                 RETURN(0);
4871         } else {
4872                 if (it->oie_file.f_pos == ldiskfs_get_htree_eof(&it->oie_file))
4873                         rc = +1;
4874                 else
4875                         rc = osd_ldiskfs_it_fill(env, di);
4876         }
4877
4878         RETURN(rc);
4879 }
4880
4881 /**
4882  * Returns the key at current position from iterator's in memory structure.
4883  *
4884  * \param di iterator's in memory structure
4885  *
4886  * \retval key i.e. struct dt_key on success
4887  */
4888 static struct dt_key *osd_it_ea_key(const struct lu_env *env,
4889                                     const struct dt_it *di)
4890 {
4891         struct osd_it_ea *it = (struct osd_it_ea *)di;
4892
4893         return (struct dt_key *)it->oie_dirent->oied_name;
4894 }
4895
4896 /**
4897  * Returns the key's size at current position from iterator's in memory structure.
4898  *
4899  * \param di iterator's in memory structure
4900  *
4901  * \retval key_size i.e. struct dt_key on success
4902  */
4903 static int osd_it_ea_key_size(const struct lu_env *env, const struct dt_it *di)
4904 {
4905         struct osd_it_ea *it = (struct osd_it_ea *)di;
4906
4907         return it->oie_dirent->oied_namelen;
4908 }
4909
4910 static int
4911 osd_dirent_update(handle_t *jh, struct super_block *sb,
4912                   struct osd_it_ea_dirent *ent, struct lu_fid *fid,
4913                   struct buffer_head *bh, struct ldiskfs_dir_entry_2 *de)
4914 {
4915         struct osd_fid_pack *rec;
4916         int                  rc;
4917         ENTRY;
4918
4919         LASSERT(de->file_type & LDISKFS_DIRENT_LUFID);
4920         LASSERT(de->rec_len >= de->name_len + sizeof(struct osd_fid_pack));
4921
4922         rc = ldiskfs_journal_get_write_access(jh, bh);
4923         if (rc != 0) {
4924                 CERROR("%.16s: fail to write access for update dirent: "
4925                        "name = %.*s, rc = %d\n",
4926                        LDISKFS_SB(sb)->s_es->s_volume_name,
4927                        ent->oied_namelen, ent->oied_name, rc);
4928                 RETURN(rc);
4929         }
4930
4931         rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
4932         fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
4933         rc = ldiskfs_journal_dirty_metadata(jh, bh);
4934         if (rc != 0)
4935                 CERROR("%.16s: fail to dirty metadata for update dirent: "
4936                        "name = %.*s, rc = %d\n",
4937                        LDISKFS_SB(sb)->s_es->s_volume_name,
4938                        ent->oied_namelen, ent->oied_name, rc);
4939
4940         RETURN(rc);
4941 }
4942
4943 static inline int
4944 osd_dirent_has_space(__u16 reclen, __u16 namelen, unsigned blocksize)
4945 {
4946         if (ldiskfs_rec_len_from_disk(reclen, blocksize) >=
4947             __LDISKFS_DIR_REC_LEN(namelen + 1 + sizeof(struct osd_fid_pack)))
4948                 return 1;
4949         else
4950                 return 0;
4951 }
4952
4953 static inline int
4954 osd_dot_dotdot_has_space(struct ldiskfs_dir_entry_2 *de, int dot_dotdot)
4955 {
4956         LASSERTF(dot_dotdot == 1 || dot_dotdot == 2,
4957                  "dot_dotdot = %d\n", dot_dotdot);
4958
4959         if (LDISKFS_DIR_REC_LEN(de) >=
4960             __LDISKFS_DIR_REC_LEN(dot_dotdot + 1 + sizeof(struct osd_fid_pack)))
4961                 return 1;
4962         else
4963                 return 0;
4964 }
4965
4966 static int
4967 osd_dirent_reinsert(const struct lu_env *env, handle_t *jh,
4968                     struct inode *dir, struct inode *inode,
4969                     struct osd_it_ea_dirent *ent, struct lu_fid *fid,
4970                     struct buffer_head *bh, struct ldiskfs_dir_entry_2 *de,
4971                     struct htree_lock *hlock)
4972 {
4973         struct dentry               *dentry;
4974         struct osd_fid_pack         *rec;
4975         struct ldiskfs_dentry_param *ldp;
4976         int                          rc;
4977         ENTRY;
4978
4979         if (!LDISKFS_HAS_INCOMPAT_FEATURE(inode->i_sb,
4980                                           LDISKFS_FEATURE_INCOMPAT_DIRDATA))
4981                 RETURN(0);
4982
4983         /* There is enough space to hold the FID-in-dirent. */
4984         if (osd_dirent_has_space(de->rec_len, ent->oied_namelen,
4985                                  dir->i_sb->s_blocksize)) {
4986                 rc = ldiskfs_journal_get_write_access(jh, bh);
4987                 if (rc != 0) {
4988                         CERROR("%.16s: fail to write access for reinsert "
4989                                "dirent: name = %.*s, rc = %d\n",
4990                                LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4991                                ent->oied_namelen, ent->oied_name, rc);
4992                         RETURN(rc);
4993                 }
4994
4995                 de->name[de->name_len] = 0;
4996                 rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
4997                 rec->fp_len = sizeof(struct lu_fid) + 1;
4998                 fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
4999                 de->file_type |= LDISKFS_DIRENT_LUFID;
5000
5001                 rc = ldiskfs_journal_dirty_metadata(jh, bh);
5002                 if (rc != 0)
5003                         CERROR("%.16s: fail to dirty metadata for reinsert "
5004                                "dirent: name = %.*s, rc = %d\n",
5005                                LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
5006                                ent->oied_namelen, ent->oied_name, rc);
5007
5008                 RETURN(rc);
5009         }
5010
5011         rc = ldiskfs_delete_entry(jh, dir, de, bh);
5012         if (rc != 0) {
5013                 CERROR("%.16s: fail to delete entry for reinsert dirent: "
5014                        "name = %.*s, rc = %d\n",
5015                        LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
5016                        ent->oied_namelen, ent->oied_name, rc);
5017                 RETURN(rc);
5018         }
5019
5020         dentry = osd_child_dentry_by_inode(env, dir, ent->oied_name,
5021                                            ent->oied_namelen);
5022         ldp = (struct ldiskfs_dentry_param *)osd_oti_get(env)->oti_ldp;
5023         osd_get_ldiskfs_dirent_param(ldp, (const struct dt_rec *)fid);
5024         dentry->d_fsdata = (void *)ldp;
5025         ll_vfs_dq_init(dir);
5026         rc = osd_ldiskfs_add_entry(jh, dentry, inode, hlock);
5027         /* It is too bad, we cannot reinsert the name entry back.
5028          * That means we lose it! */
5029         if (rc != 0)
5030                 CERROR("%.16s: fail to insert entry for reinsert dirent: "
5031                        "name = %.*s, rc = %d\n",
5032                        LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
5033                        ent->oied_namelen, ent->oied_name, rc);
5034
5035         RETURN(rc);
5036 }
5037
5038 static int
5039 osd_dirent_check_repair(const struct lu_env *env, struct osd_object *obj,
5040                         struct osd_it_ea *it, struct lu_fid *fid,
5041                         struct osd_inode_id *id, __u32 *attr)
5042 {
5043         struct osd_thread_info     *info        = osd_oti_get(env);
5044         struct lustre_mdt_attrs    *lma         = &info->oti_mdt_attrs;
5045         struct osd_device          *dev         = osd_obj2dev(obj);
5046         struct super_block         *sb          = osd_sb(dev);
5047         const char                 *devname     =
5048                                         LDISKFS_SB(sb)->s_es->s_volume_name;
5049         struct osd_it_ea_dirent    *ent         = it->oie_dirent;
5050         struct inode               *dir         = obj->oo_inode;
5051         struct htree_lock          *hlock       = NULL;
5052         struct buffer_head         *bh          = NULL;
5053         handle_t                   *jh          = NULL;
5054         struct ldiskfs_dir_entry_2 *de;
5055         struct dentry              *dentry;
5056         struct inode               *inode;
5057         int                         credits;
5058         int                         rc;
5059         int                         dot_dotdot  = 0;
5060         bool                        dirty       = false;
5061         ENTRY;
5062
5063         if (ent->oied_name[0] == '.') {
5064                 if (ent->oied_namelen == 1)
5065                         dot_dotdot = 1;
5066                 else if (ent->oied_namelen == 2 && ent->oied_name[1] == '.')
5067                         dot_dotdot = 2;
5068         }
5069
5070         dentry = osd_child_dentry_get(env, obj, ent->oied_name,
5071                                       ent->oied_namelen);
5072
5073         /* We need to ensure that the name entry is still valid.
5074          * Because it may be removed or renamed by other already.
5075          *
5076          * The unlink or rename operation will start journal before PDO lock,
5077          * so to avoid deadlock, here we need to start journal handle before
5078          * related PDO lock also. But because we do not know whether there
5079          * will be something to be repaired before PDO lock, we just start
5080          * journal without conditions.
5081          *
5082          * We may need to remove the name entry firstly, then insert back.
5083          * One credit is for user quota file update.
5084          * One credit is for group quota file update.
5085          * Two credits are for dirty inode. */
5086         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE] +
5087                   osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1 + 1 + 2;
5088
5089 again:
5090         if (dev->od_dirent_journal) {
5091                 jh = osd_journal_start_sb(sb, LDISKFS_HT_MISC, credits);
5092                 if (IS_ERR(jh)) {
5093                         rc = PTR_ERR(jh);
5094                         CERROR("%.16s: fail to start trans for dirent "
5095                                "check_repair: credits %d, name %.*s, rc %d\n",
5096                                devname, credits, ent->oied_namelen,
5097                                ent->oied_name, rc);
5098                         RETURN(rc);
5099                 }
5100
5101                 if (obj->oo_hl_head != NULL) {
5102                         hlock = osd_oti_get(env)->oti_hlock;
5103                         /* "0" means exclusive lock for the whole directory.
5104                          * We need to prevent others access such name entry
5105                          * during the delete + insert. Neither HLOCK_ADD nor
5106                          * HLOCK_DEL cannot guarantee the atomicity. */
5107                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir, 0);
5108                 } else {
5109                         down_write(&obj->oo_ext_idx_sem);
5110                 }
5111         } else {
5112                 if (obj->oo_hl_head != NULL) {
5113                         hlock = osd_oti_get(env)->oti_hlock;
5114                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir,
5115                                            LDISKFS_HLOCK_LOOKUP);
5116                 } else {
5117                         down_read(&obj->oo_ext_idx_sem);
5118                 }
5119         }
5120
5121         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
5122         /* For dot/dotdot entry, if there is not enough space to hold the
5123          * FID-in-dirent, just keep them there. It only happens when the
5124          * device upgraded from 1.8 or restored from MDT file-level backup.
5125          * For the whole directory, only dot/dotdot entry have no FID-in-dirent
5126          * and needs to get FID from LMA when readdir, it will not affect the
5127          * performance much. */
5128         if ((bh == NULL) || (le32_to_cpu(de->inode) != ent->oied_ino) ||
5129             (dot_dotdot != 0 && !osd_dot_dotdot_has_space(de, dot_dotdot))) {
5130                 *attr |= LUDA_IGNORE;
5131                 GOTO(out_journal, rc = 0);
5132         }
5133
5134         osd_id_gen(id, ent->oied_ino, OSD_OII_NOGEN);
5135         inode = osd_iget(info, dev, id);
5136         if (IS_ERR(inode)) {
5137                 rc = PTR_ERR(inode);
5138                 if (rc == -ENOENT || rc == -ESTALE) {
5139                         *attr |= LUDA_IGNORE;
5140                         rc = 0;
5141                 }
5142
5143                 GOTO(out_journal, rc);
5144         }
5145
5146         /* skip the REMOTE_PARENT_DIR. */
5147         if (inode == dev->od_mdt_map->omm_remote_parent->d_inode)
5148                 GOTO(out_inode, rc = 0);
5149
5150         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
5151         if (rc == 0) {
5152                 LASSERT(!(lma->lma_compat & LMAC_NOT_IN_OI));
5153
5154                 if (fid_is_sane(fid)) {
5155                         /* FID-in-dirent is valid. */
5156                         if (lu_fid_eq(fid, &lma->lma_self_fid))
5157                                 GOTO(out_inode, rc = 0);
5158
5159                         /* Do not repair under dryrun mode. */
5160                         if (*attr & LUDA_VERIFY_DRYRUN) {
5161                                 *attr |= LUDA_REPAIR;
5162                                 GOTO(out_inode, rc = 0);
5163                         }
5164
5165                         if (!dev->od_dirent_journal) {
5166                                 iput(inode);
5167                                 brelse(bh);
5168                                 if (hlock != NULL)
5169                                         ldiskfs_htree_unlock(hlock);
5170                                 else
5171                                         up_read(&obj->oo_ext_idx_sem);
5172                                 dev->od_dirent_journal = 1;
5173                                 goto again;
5174                         }
5175
5176                         *fid = lma->lma_self_fid;
5177                         dirty = true;
5178                         /* Update the FID-in-dirent. */
5179                         rc = osd_dirent_update(jh, sb, ent, fid, bh, de);
5180                         if (rc == 0)
5181                                 *attr |= LUDA_REPAIR;
5182                 } else {
5183                         /* Do not repair under dryrun mode. */
5184                         if (*attr & LUDA_VERIFY_DRYRUN) {
5185                                 *fid = lma->lma_self_fid;
5186                                 *attr |= LUDA_REPAIR;
5187                                 GOTO(out_inode, rc = 0);
5188                         }
5189
5190                         if (!dev->od_dirent_journal) {
5191                                 iput(inode);
5192                                 brelse(bh);
5193                                 if (hlock != NULL)
5194                                         ldiskfs_htree_unlock(hlock);
5195                                 else
5196                                         up_read(&obj->oo_ext_idx_sem);
5197                                 dev->od_dirent_journal = 1;
5198                                 goto again;
5199                         }
5200
5201                         *fid = lma->lma_self_fid;
5202                         dirty = true;
5203                         /* Append the FID-in-dirent. */
5204                         rc = osd_dirent_reinsert(env, jh, dir, inode, ent,
5205                                                  fid, bh, de, hlock);
5206                         if (rc == 0)
5207                                 *attr |= LUDA_REPAIR;
5208                 }
5209         } else if (rc == -ENODATA) {
5210                 /* Do not repair under dryrun mode. */
5211                 if (*attr & LUDA_VERIFY_DRYRUN) {
5212                         if (fid_is_sane(fid)) {
5213                                 *attr |= LUDA_REPAIR;
5214                         } else {
5215                                 lu_igif_build(fid, inode->i_ino,
5216                                               inode->i_generation);
5217                                 *attr |= LUDA_UPGRADE;
5218                         }
5219                         GOTO(out_inode, rc = 0);
5220                 }
5221
5222                 if (!dev->od_dirent_journal) {
5223                         iput(inode);
5224                         brelse(bh);
5225                         if (hlock != NULL)
5226                                 ldiskfs_htree_unlock(hlock);
5227                         else
5228                                 up_read(&obj->oo_ext_idx_sem);
5229                         dev->od_dirent_journal = 1;
5230                         goto again;
5231                 }
5232
5233                 dirty = true;
5234                 if (unlikely(fid_is_sane(fid))) {
5235                         /* FID-in-dirent exists, but FID-in-LMA is lost.
5236                          * Trust the FID-in-dirent, and add FID-in-LMA. */
5237                         rc = osd_ea_fid_set(info, inode, fid, 0, 0);
5238                         if (rc == 0)
5239                                 *attr |= LUDA_REPAIR;
5240                 } else {
5241                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
5242                         /* It is probably IGIF object. Only aappend the
5243                          * FID-in-dirent. OI scrub will process FID-in-LMA. */
5244                         rc = osd_dirent_reinsert(env, jh, dir, inode, ent,
5245                                                  fid, bh, de, hlock);
5246                         if (rc == 0)
5247                                 *attr |= LUDA_UPGRADE;
5248                 }
5249         }
5250
5251         GOTO(out_inode, rc);
5252
5253 out_inode:
5254         iput(inode);
5255
5256 out_journal:
5257         brelse(bh);
5258         if (hlock != NULL) {
5259                 ldiskfs_htree_unlock(hlock);
5260         } else {
5261                 if (dev->od_dirent_journal)
5262                         up_write(&obj->oo_ext_idx_sem);
5263                 else
5264                         up_read(&obj->oo_ext_idx_sem);
5265         }
5266         if (jh != NULL)
5267                 ldiskfs_journal_stop(jh);
5268         if (rc >= 0 && !dirty)
5269                 dev->od_dirent_journal = 0;
5270         return rc;
5271 }
5272
5273 /**
5274  * Returns the value at current position from iterator's in memory structure.
5275  *
5276  * \param di struct osd_it_ea, iterator's in memory structure
5277  * \param attr attr requested for dirent.
5278  * \param lde lustre dirent
5279  *
5280  * \retval   0 no error and \param lde has correct lustre dirent.
5281  * \retval -ve on error
5282  */
5283 static inline int osd_it_ea_rec(const struct lu_env *env,
5284                                 const struct dt_it *di,
5285                                 struct dt_rec *dtrec, __u32 attr)
5286 {
5287         struct osd_it_ea       *it    = (struct osd_it_ea *)di;
5288         struct osd_object      *obj   = it->oie_obj;
5289         struct osd_device      *dev   = osd_obj2dev(obj);
5290         struct osd_scrub       *scrub = &dev->od_scrub;
5291         struct scrub_file      *sf    = &scrub->os_file;
5292         struct osd_thread_info *oti   = osd_oti_get(env);
5293         struct osd_inode_id    *id    = &oti->oti_id;
5294         struct osd_idmap_cache *oic   = &oti->oti_cache;
5295         struct lu_fid          *fid   = &it->oie_dirent->oied_fid;
5296         struct lu_dirent       *lde   = (struct lu_dirent *)dtrec;
5297         __u32                   ino   = it->oie_dirent->oied_ino;
5298         int                     rc    = 0;
5299         ENTRY;
5300
5301         if (attr & LUDA_VERIFY) {
5302                 attr |= LUDA_TYPE;
5303                 if (unlikely(ino == osd_sb(dev)->s_root->d_inode->i_ino)) {
5304                         attr |= LUDA_IGNORE;
5305                         rc = 0;
5306                 } else {
5307                         rc = osd_dirent_check_repair(env, obj, it, fid, id,
5308                                                      &attr);
5309                 }
5310         } else {
5311                 attr &= ~LU_DIRENT_ATTRS_MASK;
5312                 if (!fid_is_sane(fid)) {
5313                         if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP))
5314                                 RETURN(-ENOENT);
5315
5316                         rc = osd_ea_fid_get(env, obj, ino, fid, id);
5317                 } else {
5318                         osd_id_gen(id, ino, OSD_OII_NOGEN);
5319                 }
5320         }
5321
5322         /* Pack the entry anyway, at least the offset is right. */
5323         osd_it_pack_dirent(lde, fid, it->oie_dirent->oied_off,
5324                            it->oie_dirent->oied_name,
5325                            it->oie_dirent->oied_namelen,
5326                            it->oie_dirent->oied_type, attr);
5327
5328         if (rc < 0)
5329                 RETURN(rc);
5330
5331         if (osd_remote_fid(env, dev, fid))
5332                 RETURN(0);
5333
5334         if (likely(!(attr & LUDA_IGNORE)))
5335                 rc = osd_add_oi_cache(oti, dev, id, fid);
5336
5337         if (!(attr & LUDA_VERIFY) &&
5338             (scrub->os_pos_current <= ino) &&
5339             ((sf->sf_flags & SF_INCONSISTENT) ||
5340              (sf->sf_flags & SF_UPGRADE && fid_is_igif(fid)) ||
5341              ldiskfs_test_bit(osd_oi_fid2idx(dev, fid), sf->sf_oi_bitmap)))
5342                 osd_consistency_check(oti, dev, oic);
5343
5344         RETURN(rc);
5345 }
5346
5347 /**
5348  * Returns a cookie for current position of the iterator head, so that
5349  * user can use this cookie to load/start the iterator next time.
5350  *
5351  * \param di iterator's in memory structure
5352  *
5353  * \retval cookie for current position, on success
5354  */
5355 static __u64 osd_it_ea_store(const struct lu_env *env, const struct dt_it *di)
5356 {
5357         struct osd_it_ea *it = (struct osd_it_ea *)di;
5358
5359         return it->oie_dirent->oied_off;
5360 }
5361
5362 /**
5363  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
5364  * to load a directory entry at a time and stored it i inn,
5365  * in iterator's in-memory data structure.
5366  *
5367  * \param di struct osd_it_ea, iterator's in memory structure
5368  *
5369  * \retval +ve on success
5370  * \retval -ve on error
5371  */
5372 static int osd_it_ea_load(const struct lu_env *env,
5373                           const struct dt_it *di, __u64 hash)
5374 {
5375         struct osd_it_ea *it = (struct osd_it_ea *)di;
5376         int rc;
5377
5378         ENTRY;
5379         it->oie_file.f_pos = hash;
5380
5381         rc =  osd_ldiskfs_it_fill(env, di);
5382         if (rc == 0)
5383                 rc = +1;
5384
5385         RETURN(rc);
5386 }
5387
5388 /**
5389  * Index lookup function for interoperability mode (b11826).
5390  *
5391  * \param key,  key i.e. file name to be searched
5392  *
5393  * \retval +ve, on success
5394  * \retval -ve, on error
5395  */
5396 static int osd_index_ea_lookup(const struct lu_env *env, struct dt_object *dt,
5397                                struct dt_rec *rec, const struct dt_key *key,
5398                                struct lustre_capa *capa)
5399 {
5400         struct osd_object *obj = osd_dt_obj(dt);
5401         int rc = 0;
5402
5403         ENTRY;
5404
5405         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
5406         LINVRNT(osd_invariant(obj));
5407
5408         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
5409                 return -EACCES;
5410
5411         rc = osd_ea_lookup_rec(env, obj, rec, key);
5412         if (rc == 0)
5413                 rc = +1;
5414         RETURN(rc);
5415 }
5416
5417 /**
5418  * Index and Iterator operations for interoperability
5419  * mode (i.e. to run 2.0 mds on 1.8 disk) (b11826)
5420  */
5421 static const struct dt_index_operations osd_index_ea_ops = {
5422         .dio_lookup         = osd_index_ea_lookup,
5423         .dio_declare_insert = osd_index_declare_ea_insert,
5424         .dio_insert         = osd_index_ea_insert,
5425         .dio_declare_delete = osd_index_declare_ea_delete,
5426         .dio_delete         = osd_index_ea_delete,
5427         .dio_it     = {
5428                 .init     = osd_it_ea_init,
5429                 .fini     = osd_it_ea_fini,
5430                 .get      = osd_it_ea_get,
5431                 .put      = osd_it_ea_put,
5432                 .next     = osd_it_ea_next,
5433                 .key      = osd_it_ea_key,
5434                 .key_size = osd_it_ea_key_size,
5435                 .rec      = osd_it_ea_rec,
5436                 .store    = osd_it_ea_store,
5437                 .load     = osd_it_ea_load
5438         }
5439 };
5440
5441 static void *osd_key_init(const struct lu_context *ctx,
5442                           struct lu_context_key *key)
5443 {
5444         struct osd_thread_info *info;
5445
5446         OBD_ALLOC_PTR(info);
5447         if (info == NULL)
5448                 return ERR_PTR(-ENOMEM);
5449
5450         OBD_ALLOC(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5451         if (info->oti_it_ea_buf == NULL)
5452                 goto out_free_info;
5453
5454         info->oti_env = container_of(ctx, struct lu_env, le_ctx);
5455
5456         info->oti_hlock = ldiskfs_htree_lock_alloc();
5457         if (info->oti_hlock == NULL)
5458                 goto out_free_ea;
5459
5460         return info;
5461
5462  out_free_ea:
5463         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5464  out_free_info:
5465         OBD_FREE_PTR(info);
5466         return ERR_PTR(-ENOMEM);
5467 }
5468
5469 static void osd_key_fini(const struct lu_context *ctx,
5470                          struct lu_context_key *key, void* data)
5471 {
5472         struct osd_thread_info *info = data;
5473
5474         if (info->oti_hlock != NULL)
5475                 ldiskfs_htree_lock_free(info->oti_hlock);
5476         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5477         lu_buf_free(&info->oti_iobuf.dr_pg_buf);
5478         lu_buf_free(&info->oti_iobuf.dr_bl_buf);
5479         OBD_FREE_PTR(info);
5480 }
5481
5482 static void osd_key_exit(const struct lu_context *ctx,
5483                          struct lu_context_key *key, void *data)
5484 {
5485         struct osd_thread_info *info = data;
5486
5487         LASSERT(info->oti_r_locks == 0);
5488         LASSERT(info->oti_w_locks == 0);
5489         LASSERT(info->oti_txns    == 0);
5490 }
5491
5492 /* type constructor/destructor: osd_type_init, osd_type_fini */
5493 LU_TYPE_INIT_FINI(osd, &osd_key);
5494
5495 struct lu_context_key osd_key = {
5496         .lct_tags = LCT_DT_THREAD | LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL,
5497         .lct_init = osd_key_init,
5498         .lct_fini = osd_key_fini,
5499         .lct_exit = osd_key_exit
5500 };
5501
5502
5503 static int osd_device_init(const struct lu_env *env, struct lu_device *d,
5504                            const char *name, struct lu_device *next)
5505 {
5506         struct osd_device *osd = osd_dev(d);
5507
5508         if (strlcpy(osd->od_svname, name, sizeof(osd->od_svname))
5509             >= sizeof(osd->od_svname))
5510                 return -E2BIG;
5511         return osd_procfs_init(osd, name);
5512 }
5513
5514 static int osd_shutdown(const struct lu_env *env, struct osd_device *o)
5515 {
5516         ENTRY;
5517
5518         /* shutdown quota slave instance associated with the device */
5519         if (o->od_quota_slave != NULL) {
5520                 qsd_fini(env, o->od_quota_slave);
5521                 o->od_quota_slave = NULL;
5522         }
5523
5524         RETURN(0);
5525 }
5526
5527 static void osd_umount(const struct lu_env *env, struct osd_device *o)
5528 {
5529         ENTRY;
5530
5531         if (o->od_mnt != NULL) {
5532                 shrink_dcache_sb(osd_sb(o));
5533                 osd_sync(env, &o->od_dt_dev);
5534
5535                 mntput(o->od_mnt);
5536                 o->od_mnt = NULL;
5537         }
5538
5539         EXIT;
5540 }
5541
5542 static int osd_mount(const struct lu_env *env,
5543                      struct osd_device *o, struct lustre_cfg *cfg)
5544 {
5545         const char              *name  = lustre_cfg_string(cfg, 0);
5546         const char              *dev  = lustre_cfg_string(cfg, 1);
5547         const char              *opts;
5548         unsigned long            page, s_flags, lmd_flags = 0;
5549         struct page             *__page;
5550         struct file_system_type *type;
5551         char                    *options = NULL;
5552         char                    *str;
5553         struct osd_thread_info  *info = osd_oti_get(env);
5554         struct lu_fid           *fid = &info->oti_fid;
5555         struct inode            *inode;
5556         int                      rc = 0;
5557         ENTRY;
5558
5559         if (o->od_mnt != NULL)
5560                 RETURN(0);
5561
5562         if (strlen(dev) >= sizeof(o->od_mntdev))
5563                 RETURN(-E2BIG);
5564         strcpy(o->od_mntdev, dev);
5565
5566         OBD_PAGE_ALLOC(__page, GFP_IOFS);
5567         if (__page == NULL)
5568                 GOTO(out, rc = -ENOMEM);
5569
5570         str = lustre_cfg_string(cfg, 2);
5571         s_flags = simple_strtoul(str, NULL, 0);
5572         str = strstr(str, ":");
5573         if (str)
5574                 lmd_flags = simple_strtoul(str + 1, NULL, 0);
5575         opts = lustre_cfg_string(cfg, 3);
5576         page = (unsigned long)page_address(__page);
5577         options = (char *)page;
5578         *options = '\0';
5579         if (opts == NULL)
5580                 strcat(options, "user_xattr,acl");
5581         else
5582                 strcat(options, opts);
5583
5584         /* Glom up mount options */
5585         if (*options != '\0')
5586                 strcat(options, ",");
5587         strlcat(options, "no_mbcache", PAGE_CACHE_SIZE);
5588
5589         type = get_fs_type("ldiskfs");
5590         if (!type) {
5591                 CERROR("%s: cannot find ldiskfs module\n", name);
5592                 GOTO(out, rc = -ENODEV);
5593         }
5594
5595         o->od_mnt = vfs_kern_mount(type, s_flags, dev, options);
5596         module_put(type->owner);
5597
5598         if (IS_ERR(o->od_mnt)) {
5599                 rc = PTR_ERR(o->od_mnt);
5600                 o->od_mnt = NULL;
5601                 CERROR("%s: can't mount %s: %d\n", name, dev, rc);
5602                 GOTO(out, rc);
5603         }
5604
5605 #ifdef HAVE_DEV_SET_RDONLY
5606         if (dev_check_rdonly(o->od_mnt->mnt_sb->s_bdev)) {
5607                 CERROR("%s: underlying device %s is marked as read-only. "
5608                        "Setup failed\n", name, dev);
5609                 GOTO(out_mnt, rc = -EROFS);
5610         }
5611 #endif
5612
5613         if (!LDISKFS_HAS_COMPAT_FEATURE(o->od_mnt->mnt_sb,
5614                                         LDISKFS_FEATURE_COMPAT_HAS_JOURNAL)) {
5615                 CERROR("%s: device %s is mounted w/o journal\n", name, dev);
5616                 GOTO(out_mnt, rc = -EINVAL);
5617         }
5618
5619 #ifdef LDISKFS_MOUNT_DIRDATA
5620         if (LDISKFS_HAS_INCOMPAT_FEATURE(o->od_mnt->mnt_sb,
5621                                          LDISKFS_FEATURE_INCOMPAT_DIRDATA))
5622                 LDISKFS_SB(osd_sb(o))->s_mount_opt |= LDISKFS_MOUNT_DIRDATA;
5623 #endif
5624         inode = osd_sb(o)->s_root->d_inode;
5625         ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NO_OI);
5626         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
5627         rc = osd_ea_fid_set(info, inode, fid, LMAC_NOT_IN_OI, 0);
5628         if (rc != 0) {
5629                 CERROR("%s: failed to set lma on %s root inode\n", name, dev);
5630                 GOTO(out_mnt, rc);
5631         }
5632
5633         if (lmd_flags & LMD_FLG_NOSCRUB)
5634                 o->od_noscrub = 1;
5635
5636         GOTO(out, rc = 0);
5637
5638 out_mnt:
5639         mntput(o->od_mnt);
5640         o->od_mnt = NULL;
5641
5642 out:
5643         if (__page)
5644                 OBD_PAGE_FREE(__page);
5645
5646         return rc;
5647 }
5648
5649 static struct lu_device *osd_device_fini(const struct lu_env *env,
5650                                          struct lu_device *d)
5651 {
5652         struct osd_device *o = osd_dev(d);
5653         ENTRY;
5654
5655         osd_shutdown(env, o);
5656         osd_procfs_fini(o);
5657         osd_scrub_cleanup(env, o);
5658         osd_obj_map_fini(o);
5659         osd_umount(env, o);
5660
5661         RETURN(NULL);
5662 }
5663
5664 static int osd_device_init0(const struct lu_env *env,
5665                             struct osd_device *o,
5666                             struct lustre_cfg *cfg)
5667 {
5668         struct lu_device        *l = osd2lu_dev(o);
5669         struct osd_thread_info *info;
5670         int                     rc;
5671         int                     cplen = 0;
5672
5673         /* if the module was re-loaded, env can loose its keys */
5674         rc = lu_env_refill((struct lu_env *) env);
5675         if (rc)
5676                 GOTO(out, rc);
5677         info = osd_oti_get(env);
5678         LASSERT(info);
5679
5680         l->ld_ops = &osd_lu_ops;
5681         o->od_dt_dev.dd_ops = &osd_dt_ops;
5682
5683         spin_lock_init(&o->od_osfs_lock);
5684         mutex_init(&o->od_otable_mutex);
5685         o->od_osfs_age = cfs_time_shift_64(-1000);
5686
5687         o->od_capa_hash = init_capa_hash();
5688         if (o->od_capa_hash == NULL)
5689                 GOTO(out, rc = -ENOMEM);
5690
5691         o->od_read_cache = 1;
5692         o->od_writethrough_cache = 1;
5693         o->od_readcache_max_filesize = OSD_MAX_CACHE_SIZE;
5694
5695         rc = osd_mount(env, o, cfg);
5696         if (rc)
5697                 GOTO(out_capa, rc);
5698
5699         cplen = strlcpy(o->od_svname, lustre_cfg_string(cfg, 4),
5700                         sizeof(o->od_svname));
5701         if (cplen >= sizeof(o->od_svname)) {
5702                 rc = -E2BIG;
5703                 GOTO(out_mnt, rc);
5704         }
5705
5706         if (server_name_is_ost(o->od_svname))
5707                 o->od_is_ost = 1;
5708
5709         rc = osd_obj_map_init(env, o);
5710         if (rc != 0)
5711                 GOTO(out_mnt, rc);
5712
5713         rc = lu_site_init(&o->od_site, l);
5714         if (rc != 0)
5715                 GOTO(out_compat, rc);
5716         o->od_site.ls_bottom_dev = l;
5717
5718         rc = lu_site_init_finish(&o->od_site);
5719         if (rc != 0)
5720                 GOTO(out_site, rc);
5721
5722         /* self-repair LMA by default */
5723         o->od_lma_self_repair = 1;
5724
5725         CFS_INIT_LIST_HEAD(&o->od_ios_list);
5726         /* setup scrub, including OI files initialization */
5727         rc = osd_scrub_setup(env, o);
5728         if (rc < 0)
5729                 GOTO(out_site, rc);
5730
5731         rc = osd_procfs_init(o, o->od_svname);
5732         if (rc != 0) {
5733                 CERROR("%s: can't initialize procfs: rc = %d\n",
5734                        o->od_svname, rc);
5735                 GOTO(out_scrub, rc);
5736         }
5737
5738         LASSERT(l->ld_site->ls_linkage.next && l->ld_site->ls_linkage.prev);
5739
5740         /* initialize quota slave instance */
5741         o->od_quota_slave = qsd_init(env, o->od_svname, &o->od_dt_dev,
5742                                      o->od_proc_entry);
5743         if (IS_ERR(o->od_quota_slave)) {
5744                 rc = PTR_ERR(o->od_quota_slave);
5745                 o->od_quota_slave = NULL;
5746                 GOTO(out_procfs, rc);
5747         }
5748
5749         RETURN(0);
5750
5751 out_procfs:
5752         osd_procfs_fini(o);
5753 out_scrub:
5754         osd_scrub_cleanup(env, o);
5755 out_site:
5756         lu_site_fini(&o->od_site);
5757 out_compat:
5758         osd_obj_map_fini(o);
5759 out_mnt:
5760         osd_umount(env, o);
5761 out_capa:
5762         cleanup_capa_hash(o->od_capa_hash);
5763 out:
5764         return rc;
5765 }
5766
5767 static struct lu_device *osd_device_alloc(const struct lu_env *env,
5768                                           struct lu_device_type *t,
5769                                           struct lustre_cfg *cfg)
5770 {
5771         struct osd_device *o;
5772         int                rc;
5773
5774         OBD_ALLOC_PTR(o);
5775         if (o == NULL)
5776                 return ERR_PTR(-ENOMEM);
5777
5778         rc = dt_device_init(&o->od_dt_dev, t);
5779         if (rc == 0) {
5780                 /* Because the ctx might be revived in dt_device_init,
5781                  * refill the env here */
5782                 lu_env_refill((struct lu_env *)env);
5783                 rc = osd_device_init0(env, o, cfg);
5784                 if (rc)
5785                         dt_device_fini(&o->od_dt_dev);
5786         }
5787
5788         if (unlikely(rc != 0))
5789                 OBD_FREE_PTR(o);
5790
5791         return rc == 0 ? osd2lu_dev(o) : ERR_PTR(rc);
5792 }
5793
5794 static struct lu_device *osd_device_free(const struct lu_env *env,
5795                                          struct lu_device *d)
5796 {
5797         struct osd_device *o = osd_dev(d);
5798         ENTRY;
5799
5800         cleanup_capa_hash(o->od_capa_hash);
5801         /* XXX: make osd top device in order to release reference */
5802         d->ld_site->ls_top_dev = d;
5803         lu_site_purge(env, d->ld_site, -1);
5804         if (!cfs_hash_is_empty(d->ld_site->ls_obj_hash)) {
5805                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, D_ERROR, NULL);
5806                 lu_site_print(env, d->ld_site, &msgdata, lu_cdebug_printer);
5807         }
5808         lu_site_fini(&o->od_site);
5809         dt_device_fini(&o->od_dt_dev);
5810         OBD_FREE_PTR(o);
5811         RETURN(NULL);
5812 }
5813
5814 static int osd_process_config(const struct lu_env *env,
5815                               struct lu_device *d, struct lustre_cfg *cfg)
5816 {
5817         struct osd_device               *o = osd_dev(d);
5818         int                             rc;
5819         ENTRY;
5820
5821         switch (cfg->lcfg_command) {
5822         case LCFG_SETUP:
5823                 rc = osd_mount(env, o, cfg);
5824                 break;
5825         case LCFG_CLEANUP:
5826                 lu_dev_del_linkage(d->ld_site, d);
5827                 rc = osd_shutdown(env, o);
5828                 break;
5829         case LCFG_PARAM:
5830                 LASSERT(&o->od_dt_dev);
5831                 rc = class_process_proc_param(PARAM_OSD, lprocfs_osd_obd_vars,
5832                                               cfg, &o->od_dt_dev);
5833                 if (rc > 0 || rc == -ENOSYS)
5834                         rc = class_process_proc_param(PARAM_OST,
5835                                                       lprocfs_osd_obd_vars,
5836                                                       cfg, &o->od_dt_dev);
5837                 break;
5838         default:
5839                 rc = -ENOSYS;
5840         }
5841
5842         RETURN(rc);
5843 }
5844
5845 static int osd_recovery_complete(const struct lu_env *env,
5846                                  struct lu_device *d)
5847 {
5848         struct osd_device       *osd = osd_dev(d);
5849         int                      rc = 0;
5850         ENTRY;
5851
5852         if (osd->od_quota_slave == NULL)
5853                 RETURN(0);
5854
5855         /* start qsd instance on recovery completion, this notifies the quota
5856          * slave code that we are about to process new requests now */
5857         rc = qsd_start(env, osd->od_quota_slave);
5858         RETURN(rc);
5859 }
5860
5861 /*
5862  * we use exports to track all osd users
5863  */
5864 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
5865                            struct obd_device *obd, struct obd_uuid *cluuid,
5866                            struct obd_connect_data *data, void *localdata)
5867 {
5868         struct osd_device    *osd = osd_dev(obd->obd_lu_dev);
5869         struct lustre_handle  conn;
5870         int                   rc;
5871         ENTRY;
5872
5873         CDEBUG(D_CONFIG, "connect #%d\n", osd->od_connects);
5874
5875         rc = class_connect(&conn, obd, cluuid);
5876         if (rc)
5877                 RETURN(rc);
5878
5879         *exp = class_conn2export(&conn);
5880
5881         spin_lock(&osd->od_osfs_lock);
5882         osd->od_connects++;
5883         spin_unlock(&osd->od_osfs_lock);
5884
5885         RETURN(0);
5886 }
5887
5888 /*
5889  * once last export (we don't count self-export) disappeared
5890  * osd can be released
5891  */
5892 static int osd_obd_disconnect(struct obd_export *exp)
5893 {
5894         struct obd_device *obd = exp->exp_obd;
5895         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
5896         int                rc, release = 0;
5897         ENTRY;
5898
5899         /* Only disconnect the underlying layers on the final disconnect. */
5900         spin_lock(&osd->od_osfs_lock);
5901         osd->od_connects--;
5902         if (osd->od_connects == 0)
5903                 release = 1;
5904         spin_unlock(&osd->od_osfs_lock);
5905
5906         rc = class_disconnect(exp); /* bz 9811 */
5907
5908         if (rc == 0 && release)
5909                 class_manual_cleanup(obd);
5910         RETURN(rc);
5911 }
5912
5913 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
5914                        struct lu_device *dev)
5915 {
5916         struct osd_device *osd = osd_dev(dev);
5917         int                result = 0;
5918         ENTRY;
5919
5920         if (osd->od_quota_slave != NULL)
5921                 /* set up quota slave objects */
5922                 result = qsd_prepare(env, osd->od_quota_slave);
5923
5924         RETURN(result);
5925 }
5926
5927 static const struct lu_object_operations osd_lu_obj_ops = {
5928         .loo_object_init      = osd_object_init,
5929         .loo_object_delete    = osd_object_delete,
5930         .loo_object_release   = osd_object_release,
5931         .loo_object_free      = osd_object_free,
5932         .loo_object_print     = osd_object_print,
5933         .loo_object_invariant = osd_object_invariant
5934 };
5935
5936 const struct lu_device_operations osd_lu_ops = {
5937         .ldo_object_alloc      = osd_object_alloc,
5938         .ldo_process_config    = osd_process_config,
5939         .ldo_recovery_complete = osd_recovery_complete,
5940         .ldo_prepare           = osd_prepare,
5941 };
5942
5943 static const struct lu_device_type_operations osd_device_type_ops = {
5944         .ldto_init = osd_type_init,
5945         .ldto_fini = osd_type_fini,
5946
5947         .ldto_start = osd_type_start,
5948         .ldto_stop  = osd_type_stop,
5949
5950         .ldto_device_alloc = osd_device_alloc,
5951         .ldto_device_free  = osd_device_free,
5952
5953         .ldto_device_init    = osd_device_init,
5954         .ldto_device_fini    = osd_device_fini
5955 };
5956
5957 struct lu_device_type osd_device_type = {
5958         .ldt_tags     = LU_DEVICE_DT,
5959         .ldt_name     = LUSTRE_OSD_LDISKFS_NAME,
5960         .ldt_ops      = &osd_device_type_ops,
5961         .ldt_ctx_tags = LCT_LOCAL,
5962 };
5963
5964 /*
5965  * lprocfs legacy support.
5966  */
5967 static struct obd_ops osd_obd_device_ops = {
5968         .o_owner = THIS_MODULE,
5969         .o_connect      = osd_obd_connect,
5970         .o_disconnect   = osd_obd_disconnect
5971 };
5972
5973 static int __init osd_mod_init(void)
5974 {
5975         int rc;
5976
5977         osd_oi_mod_init();
5978
5979         rc = lu_kmem_init(ldiskfs_caches);
5980         if (rc)
5981                 return rc;
5982
5983         rc = class_register_type(&osd_obd_device_ops, NULL, NULL,
5984 #ifndef HAVE_ONLY_PROCFS_SEQ
5985                                 lprocfs_osd_module_vars,
5986 #endif
5987                                 LUSTRE_OSD_LDISKFS_NAME, &osd_device_type);
5988         if (rc)
5989                 lu_kmem_fini(ldiskfs_caches);
5990         return rc;
5991 }
5992
5993 static void __exit osd_mod_exit(void)
5994 {
5995         class_unregister_type(LUSTRE_OSD_LDISKFS_NAME);
5996         lu_kmem_fini(ldiskfs_caches);
5997 }
5998
5999 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
6000 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_LDISKFS_NAME")");
6001 MODULE_LICENSE("GPL");
6002
6003 cfs_module(osd, "0.1.0", osd_mod_init, osd_mod_exit);