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