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