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