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