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