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