Whamcloud - gitweb
LU-3915 osd-ldiskfs: don't assert on possible upgrade
[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         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         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
2660
2661         LINVRNT(osd_invariant(obj));
2662         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2663         LASSERT(osd_write_locked(env, obj));
2664         LASSERT(th != NULL);
2665
2666         osd_trans_exec_op(env, th, OSD_OT_REF_DEL);
2667
2668         spin_lock(&obj->oo_guard);
2669         /* That can be result of upgrade from old Lustre version and
2670          * applied only to local files.  Just skip this ref_del call.
2671          * ext4_unlink() only treats this as a warning, don't LASSERT here.*/
2672         if (inode->i_nlink == 0) {
2673                 CDEBUG_LIMIT(fid_is_norm(lu_object_fid(&dt->do_lu)) ?
2674                              D_ERROR : D_INODE, "%s: nlink == 0 on "DFID
2675                              ", maybe an upgraded file? (LU-3915)\n",
2676                              osd_name(osd), PFID(lu_object_fid(&dt->do_lu)));
2677                 spin_unlock(&obj->oo_guard);
2678                 return 0;
2679         }
2680
2681         /* This based on ldiskfs_dec_count(), which is not exported.
2682          *
2683          * If a directory already has nlink == 1, then do not drop the nlink
2684          * count to 0, even temporarily, to avoid race conditions with other
2685          * threads not holding oo_guard seeing i_nlink == 0 in rare cases.
2686          *
2687          * nlink == 1 means the directory has/had > EXT4_LINK_MAX subdirs.
2688          */
2689         if (!S_ISDIR(inode->i_mode) || inode->i_nlink > 1) {
2690                 drop_nlink(inode);
2691
2692                 spin_unlock(&obj->oo_guard);
2693                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2694                 LINVRNT(osd_invariant(obj));
2695         } else {
2696                 spin_unlock(&obj->oo_guard);
2697         }
2698
2699         return 0;
2700 }
2701
2702 /*
2703  * Get the 64-bit version for an inode.
2704  */
2705 static int osd_object_version_get(const struct lu_env *env,
2706                                   struct dt_object *dt, dt_obj_version_t *ver)
2707 {
2708         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2709
2710         CDEBUG(D_INODE, "Get version "LPX64" for inode %lu\n",
2711                LDISKFS_I(inode)->i_fs_version, inode->i_ino);
2712         *ver = LDISKFS_I(inode)->i_fs_version;
2713         return 0;
2714 }
2715
2716 /*
2717  * Concurrency: @dt is read locked.
2718  */
2719 static int osd_xattr_get(const struct lu_env *env, struct dt_object *dt,
2720                          struct lu_buf *buf, const char *name,
2721                          struct lustre_capa *capa)
2722 {
2723         struct osd_object      *obj    = osd_dt_obj(dt);
2724         struct inode           *inode  = obj->oo_inode;
2725         struct osd_thread_info *info   = osd_oti_get(env);
2726         struct dentry          *dentry = &info->oti_obj_dentry;
2727
2728         /* version get is not real XATTR but uses xattr API */
2729         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2730                 /* for version we are just using xattr API but change inode
2731                  * field instead */
2732                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
2733                 osd_object_version_get(env, dt, buf->lb_buf);
2734                 return sizeof(dt_obj_version_t);
2735         }
2736
2737         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2738         LASSERT(inode->i_op != NULL && inode->i_op->getxattr != NULL);
2739
2740         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
2741                 return -EACCES;
2742
2743         return __osd_xattr_get(inode, dentry, name, buf->lb_buf, buf->lb_len);
2744 }
2745
2746
2747 static int osd_declare_xattr_set(const struct lu_env *env,
2748                                  struct dt_object *dt,
2749                                  const struct lu_buf *buf, const char *name,
2750                                  int fl, struct thandle *handle)
2751 {
2752         struct osd_thandle *oh;
2753
2754         LASSERT(handle != NULL);
2755
2756         oh = container_of0(handle, struct osd_thandle, ot_super);
2757         LASSERT(oh->ot_handle == NULL);
2758
2759         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2760                              strcmp(name, XATTR_NAME_VERSION) == 0 ?
2761                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE] :
2762                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2763
2764         return 0;
2765 }
2766
2767 /*
2768  * Set the 64-bit version for object
2769  */
2770 static void osd_object_version_set(const struct lu_env *env,
2771                                    struct dt_object *dt,
2772                                    dt_obj_version_t *new_version)
2773 {
2774         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2775
2776         CDEBUG(D_INODE, "Set version "LPX64" (old "LPX64") for inode %lu\n",
2777                *new_version, LDISKFS_I(inode)->i_fs_version, inode->i_ino);
2778
2779         LDISKFS_I(inode)->i_fs_version = *new_version;
2780         /** Version is set after all inode operations are finished,
2781          *  so we should mark it dirty here */
2782         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2783 }
2784
2785 /*
2786  * Concurrency: @dt is write locked.
2787  */
2788 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
2789                          const struct lu_buf *buf, const char *name, int fl,
2790                          struct thandle *handle, struct lustre_capa *capa)
2791 {
2792         struct osd_object      *obj      = osd_dt_obj(dt);
2793         struct inode           *inode    = obj->oo_inode;
2794         struct osd_thread_info *info     = osd_oti_get(env);
2795         int                     fs_flags = 0;
2796         ENTRY;
2797
2798         LASSERT(handle != NULL);
2799
2800         /* version set is not real XATTR */
2801         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2802                 /* for version we are just using xattr API but change inode
2803                  * field instead */
2804                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
2805                 osd_object_version_set(env, dt, buf->lb_buf);
2806                 return sizeof(dt_obj_version_t);
2807         }
2808
2809         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
2810                 return -EACCES;
2811
2812         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
2813         if (fl & LU_XATTR_REPLACE)
2814                 fs_flags |= XATTR_REPLACE;
2815
2816         if (fl & LU_XATTR_CREATE)
2817                 fs_flags |= XATTR_CREATE;
2818
2819         return __osd_xattr_set(info, inode, name, buf->lb_buf, buf->lb_len,
2820                                fs_flags);
2821 }
2822
2823 /*
2824  * Concurrency: @dt is read locked.
2825  */
2826 static int osd_xattr_list(const struct lu_env *env, struct dt_object *dt,
2827                           struct lu_buf *buf, struct lustre_capa *capa)
2828 {
2829         struct osd_object      *obj    = osd_dt_obj(dt);
2830         struct inode           *inode  = obj->oo_inode;
2831         struct osd_thread_info *info   = osd_oti_get(env);
2832         struct dentry          *dentry = &info->oti_obj_dentry;
2833
2834         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2835         LASSERT(inode->i_op != NULL && inode->i_op->listxattr != NULL);
2836         LASSERT(osd_read_locked(env, obj) || osd_write_locked(env, obj));
2837
2838         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
2839                 return -EACCES;
2840
2841         dentry->d_inode = inode;
2842         dentry->d_sb = inode->i_sb;
2843         return inode->i_op->listxattr(dentry, buf->lb_buf, buf->lb_len);
2844 }
2845
2846 static int osd_declare_xattr_del(const struct lu_env *env,
2847                                  struct dt_object *dt, const char *name,
2848                                  struct thandle *handle)
2849 {
2850         struct osd_thandle *oh;
2851
2852         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2853         LASSERT(handle != NULL);
2854
2855         oh = container_of0(handle, struct osd_thandle, ot_super);
2856         LASSERT(oh->ot_handle == NULL);
2857
2858         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2859                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2860
2861         return 0;
2862 }
2863
2864 /*
2865  * Concurrency: @dt is write locked.
2866  */
2867 static int osd_xattr_del(const struct lu_env *env, struct dt_object *dt,
2868                          const char *name, struct thandle *handle,
2869                          struct lustre_capa *capa)
2870 {
2871         struct osd_object      *obj    = osd_dt_obj(dt);
2872         struct inode           *inode  = obj->oo_inode;
2873         struct osd_thread_info *info   = osd_oti_get(env);
2874         struct dentry          *dentry = &info->oti_obj_dentry;
2875         int                     rc;
2876
2877         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2878         LASSERT(inode->i_op != NULL && inode->i_op->removexattr != NULL);
2879         LASSERT(handle != NULL);
2880
2881         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
2882                 return -EACCES;
2883
2884         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
2885
2886         ll_vfs_dq_init(inode);
2887         dentry->d_inode = inode;
2888         dentry->d_sb = inode->i_sb;
2889         rc = inode->i_op->removexattr(dentry, name);
2890         return rc;
2891 }
2892
2893 static struct obd_capa *osd_capa_get(const struct lu_env *env,
2894                                      struct dt_object *dt,
2895                                      struct lustre_capa *old, __u64 opc)
2896 {
2897         struct osd_thread_info *info = osd_oti_get(env);
2898         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
2899         struct osd_object *obj = osd_dt_obj(dt);
2900         struct osd_device *osd = osd_obj2dev(obj);
2901         struct lustre_capa_key *key = &info->oti_capa_key;
2902         struct lustre_capa *capa = &info->oti_capa;
2903         struct obd_capa *oc;
2904         struct lu_capainfo *lci;
2905         int rc;
2906         ENTRY;
2907
2908         if (!osd->od_fl_capa)
2909                 RETURN(ERR_PTR(-ENOENT));
2910
2911         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2912         LINVRNT(osd_invariant(obj));
2913
2914         /* renewal sanity check */
2915         if (old && osd_object_auth(env, dt, old, opc))
2916                 RETURN(ERR_PTR(-EACCES));
2917
2918         lci = lu_capainfo_get(env);
2919         if (unlikely(lci == NULL))
2920                 RETURN(ERR_PTR(-ENOENT));
2921
2922         switch (lci->lci_auth) {
2923         case LC_ID_NONE:
2924                 RETURN(NULL);
2925         case LC_ID_PLAIN:
2926                 capa->lc_uid = obj->oo_inode->i_uid;
2927                 capa->lc_gid = obj->oo_inode->i_gid;
2928                 capa->lc_flags = LC_ID_PLAIN;
2929                 break;
2930         case LC_ID_CONVERT: {
2931                 __u32 d[4], s[4];
2932
2933                 s[0] = obj->oo_inode->i_uid;
2934                 cfs_get_random_bytes(&(s[1]), sizeof(__u32));
2935                 s[2] = obj->oo_inode->i_gid;
2936                 cfs_get_random_bytes(&(s[3]), sizeof(__u32));
2937                 rc = capa_encrypt_id(d, s, key->lk_key, CAPA_HMAC_KEY_MAX_LEN);
2938                 if (unlikely(rc))
2939                         RETURN(ERR_PTR(rc));
2940
2941                 capa->lc_uid   = ((__u64)d[1] << 32) | d[0];
2942                 capa->lc_gid   = ((__u64)d[3] << 32) | d[2];
2943                 capa->lc_flags = LC_ID_CONVERT;
2944                 break;
2945         }
2946         default:
2947                 RETURN(ERR_PTR(-EINVAL));
2948         }
2949
2950         capa->lc_fid = *fid;
2951         capa->lc_opc = opc;
2952         capa->lc_flags |= osd->od_capa_alg << 24;
2953         capa->lc_timeout = osd->od_capa_timeout;
2954         capa->lc_expiry = 0;
2955
2956         oc = capa_lookup(osd->od_capa_hash, capa, 1);
2957         if (oc) {
2958                 LASSERT(!capa_is_expired(oc));
2959                 RETURN(oc);
2960         }
2961
2962         spin_lock(&capa_lock);
2963         *key = osd->od_capa_keys[1];
2964         spin_unlock(&capa_lock);
2965
2966         capa->lc_keyid = key->lk_keyid;
2967         capa->lc_expiry = cfs_time_current_sec() + osd->od_capa_timeout;
2968
2969         rc = capa_hmac(capa->lc_hmac, capa, key->lk_key);
2970         if (rc) {
2971                 DEBUG_CAPA(D_ERROR, capa, "HMAC failed: %d for", rc);
2972                 RETURN(ERR_PTR(rc));
2973         }
2974
2975         oc = capa_add(osd->od_capa_hash, capa);
2976         RETURN(oc);
2977 }
2978
2979 static int osd_object_sync(const struct lu_env *env, struct dt_object *dt)
2980 {
2981         struct osd_object       *obj    = osd_dt_obj(dt);
2982         struct inode            *inode  = obj->oo_inode;
2983         struct osd_thread_info  *info   = osd_oti_get(env);
2984         struct dentry           *dentry = &info->oti_obj_dentry;
2985         struct file             *file   = &info->oti_file;
2986         int                     rc;
2987
2988         ENTRY;
2989
2990         dentry->d_inode = inode;
2991         dentry->d_sb = inode->i_sb;
2992         file->f_dentry = dentry;
2993         file->f_mapping = inode->i_mapping;
2994         file->f_op = inode->i_fop;
2995 #ifndef HAVE_FILE_FSYNC_4ARGS
2996         mutex_lock(&inode->i_mutex);
2997 #endif
2998         rc = do_fsync(file, 0);
2999 #ifndef HAVE_FILE_FSYNC_4ARGS
3000         mutex_unlock(&inode->i_mutex);
3001 #endif
3002         RETURN(rc);
3003 }
3004
3005 static int osd_data_get(const struct lu_env *env, struct dt_object *dt,
3006                         void **data)
3007 {
3008         struct osd_object *obj = osd_dt_obj(dt);
3009         ENTRY;
3010
3011         *data = (void *)obj->oo_inode;
3012         RETURN(0);
3013 }
3014
3015 /*
3016  * Index operations.
3017  */
3018
3019 static int osd_iam_index_probe(const struct lu_env *env, struct osd_object *o,
3020                            const struct dt_index_features *feat)
3021 {
3022         struct iam_descr *descr;
3023
3024         if (osd_object_is_root(o))
3025                 return feat == &dt_directory_features;
3026
3027         LASSERT(o->oo_dir != NULL);
3028
3029         descr = o->oo_dir->od_container.ic_descr;
3030         if (feat == &dt_directory_features) {
3031                 if (descr->id_rec_size == sizeof(struct osd_fid_pack))
3032                         return 1;
3033                 else
3034                         return 0;
3035         } else {
3036                 return
3037                         feat->dif_keysize_min <= descr->id_key_size &&
3038                         descr->id_key_size <= feat->dif_keysize_max &&
3039                         feat->dif_recsize_min <= descr->id_rec_size &&
3040                         descr->id_rec_size <= feat->dif_recsize_max &&
3041                         !(feat->dif_flags & (DT_IND_VARKEY |
3042                                              DT_IND_VARREC | DT_IND_NONUNQ)) &&
3043                         ergo(feat->dif_flags & DT_IND_UPDATE,
3044                              1 /* XXX check that object (and file system) is
3045                                 * writable */);
3046         }
3047 }
3048
3049 static int osd_iam_container_init(const struct lu_env *env,
3050                                   struct osd_object *obj,
3051                                   struct osd_directory *dir)
3052 {
3053         struct iam_container *bag = &dir->od_container;
3054         int result;
3055
3056         result = iam_container_init(bag, &dir->od_descr, obj->oo_inode);
3057         if (result != 0)
3058                 return result;
3059
3060         result = iam_container_setup(bag);
3061         if (result == 0)
3062                 obj->oo_dt.do_index_ops = &osd_index_iam_ops;
3063         else
3064                 iam_container_fini(bag);
3065
3066         return result;
3067 }
3068
3069
3070 /*
3071  * Concurrency: no external locking is necessary.
3072  */
3073 static int osd_index_try(const struct lu_env *env, struct dt_object *dt,
3074                          const struct dt_index_features *feat)
3075 {
3076         int                      result;
3077         int                      skip_iam = 0;
3078         struct osd_object       *obj = osd_dt_obj(dt);
3079
3080         LINVRNT(osd_invariant(obj));
3081
3082         if (osd_object_is_root(obj)) {
3083                 dt->do_index_ops = &osd_index_ea_ops;
3084                 result = 0;
3085         } else if (feat == &dt_directory_features) {
3086                 dt->do_index_ops = &osd_index_ea_ops;
3087                 if (obj->oo_inode != NULL && S_ISDIR(obj->oo_inode->i_mode))
3088                         result = 0;
3089                 else
3090                         result = -ENOTDIR;
3091                 skip_iam = 1;
3092         } else if (unlikely(feat == &dt_otable_features)) {
3093                 dt->do_index_ops = &osd_otable_ops;
3094                 return 0;
3095         } else if (unlikely(feat == &dt_acct_features)) {
3096                 dt->do_index_ops = &osd_acct_index_ops;
3097                 result = 0;
3098                 skip_iam = 1;
3099         } else if (!osd_has_index(obj)) {
3100                 struct osd_directory *dir;
3101
3102                 OBD_ALLOC_PTR(dir);
3103                 if (dir != NULL) {
3104
3105                         spin_lock(&obj->oo_guard);
3106                         if (obj->oo_dir == NULL)
3107                                 obj->oo_dir = dir;
3108                         else
3109                                 /*
3110                                  * Concurrent thread allocated container data.
3111                                  */
3112                                 OBD_FREE_PTR(dir);
3113                         spin_unlock(&obj->oo_guard);
3114                         /*
3115                          * Now, that we have container data, serialize its
3116                          * initialization.
3117                          */
3118                         down_write(&obj->oo_ext_idx_sem);
3119                         /*
3120                          * recheck under lock.
3121                          */
3122                         if (!osd_has_index(obj))
3123                                 result = osd_iam_container_init(env, obj, dir);
3124                         else
3125                                 result = 0;
3126                         up_write(&obj->oo_ext_idx_sem);
3127                 } else {
3128                         result = -ENOMEM;
3129                 }
3130         } else {
3131                 result = 0;
3132         }
3133
3134         if (result == 0 && skip_iam == 0) {
3135                 if (!osd_iam_index_probe(env, obj, feat))
3136                         result = -ENOTDIR;
3137         }
3138         LINVRNT(osd_invariant(obj));
3139
3140         if (result == 0 && is_quota_glb_feat(feat) &&
3141             fid_seq(lu_object_fid(&dt->do_lu)) == FID_SEQ_QUOTA_GLB)
3142                 result = osd_quota_migration(env, dt, feat);
3143
3144         return result;
3145 }
3146
3147 static int osd_otable_it_attr_get(const struct lu_env *env,
3148                                  struct dt_object *dt,
3149                                  struct lu_attr *attr,
3150                                  struct lustre_capa *capa)
3151 {
3152         attr->la_valid = 0;
3153         return 0;
3154 }
3155
3156 static const struct dt_object_operations osd_obj_ops = {
3157         .do_read_lock         = osd_object_read_lock,
3158         .do_write_lock        = osd_object_write_lock,
3159         .do_read_unlock       = osd_object_read_unlock,
3160         .do_write_unlock      = osd_object_write_unlock,
3161         .do_write_locked      = osd_object_write_locked,
3162         .do_attr_get          = osd_attr_get,
3163         .do_declare_attr_set  = osd_declare_attr_set,
3164         .do_attr_set          = osd_attr_set,
3165         .do_ah_init           = osd_ah_init,
3166         .do_declare_create    = osd_declare_object_create,
3167         .do_create            = osd_object_create,
3168         .do_declare_destroy   = osd_declare_object_destroy,
3169         .do_destroy           = osd_object_destroy,
3170         .do_index_try         = osd_index_try,
3171         .do_declare_ref_add   = osd_declare_object_ref_add,
3172         .do_ref_add           = osd_object_ref_add,
3173         .do_declare_ref_del   = osd_declare_object_ref_del,
3174         .do_ref_del           = osd_object_ref_del,
3175         .do_xattr_get         = osd_xattr_get,
3176         .do_declare_xattr_set = osd_declare_xattr_set,
3177         .do_xattr_set         = osd_xattr_set,
3178         .do_declare_xattr_del = osd_declare_xattr_del,
3179         .do_xattr_del         = osd_xattr_del,
3180         .do_xattr_list        = osd_xattr_list,
3181         .do_capa_get          = osd_capa_get,
3182         .do_object_sync       = osd_object_sync,
3183         .do_data_get          = osd_data_get,
3184 };
3185
3186 /**
3187  * dt_object_operations for interoperability mode
3188  * (i.e. to run 2.0 mds on 1.8 disk) (b11826)
3189  */
3190 static const struct dt_object_operations osd_obj_ea_ops = {
3191         .do_read_lock         = osd_object_read_lock,
3192         .do_write_lock        = osd_object_write_lock,
3193         .do_read_unlock       = osd_object_read_unlock,
3194         .do_write_unlock      = osd_object_write_unlock,
3195         .do_write_locked      = osd_object_write_locked,
3196         .do_attr_get          = osd_attr_get,
3197         .do_declare_attr_set  = osd_declare_attr_set,
3198         .do_attr_set          = osd_attr_set,
3199         .do_ah_init           = osd_ah_init,
3200         .do_declare_create    = osd_declare_object_create,
3201         .do_create            = osd_object_ea_create,
3202         .do_declare_destroy   = osd_declare_object_destroy,
3203         .do_destroy           = osd_object_destroy,
3204         .do_index_try         = osd_index_try,
3205         .do_declare_ref_add   = osd_declare_object_ref_add,
3206         .do_ref_add           = osd_object_ref_add,
3207         .do_declare_ref_del   = osd_declare_object_ref_del,
3208         .do_ref_del           = osd_object_ref_del,
3209         .do_xattr_get         = osd_xattr_get,
3210         .do_declare_xattr_set = osd_declare_xattr_set,
3211         .do_xattr_set         = osd_xattr_set,
3212         .do_declare_xattr_del = osd_declare_xattr_del,
3213         .do_xattr_del         = osd_xattr_del,
3214         .do_xattr_list        = osd_xattr_list,
3215         .do_capa_get          = osd_capa_get,
3216         .do_object_sync       = osd_object_sync,
3217         .do_data_get          = osd_data_get,
3218 };
3219
3220 static const struct dt_object_operations osd_obj_otable_it_ops = {
3221         .do_attr_get    = osd_otable_it_attr_get,
3222         .do_index_try   = osd_index_try,
3223 };
3224
3225 static int osd_index_declare_iam_delete(const struct lu_env *env,
3226                                         struct dt_object *dt,
3227                                         const struct dt_key *key,
3228                                         struct thandle *handle)
3229 {
3230         struct osd_thandle    *oh;
3231
3232         oh = container_of0(handle, struct osd_thandle, ot_super);
3233         LASSERT(oh->ot_handle == NULL);
3234
3235         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3236                              osd_dto_credits_noquota[DTO_INDEX_DELETE]);
3237
3238         return 0;
3239 }
3240
3241 /**
3242  *      delete a (key, value) pair from index \a dt specified by \a key
3243  *
3244  *      \param  dt      osd index object
3245  *      \param  key     key for index
3246  *      \param  rec     record reference
3247  *      \param  handle  transaction handler
3248  *
3249  *      \retval  0  success
3250  *      \retval -ve   failure
3251  */
3252
3253 static int osd_index_iam_delete(const struct lu_env *env, struct dt_object *dt,
3254                                 const struct dt_key *key,
3255                                 struct thandle *handle,
3256                                 struct lustre_capa *capa)
3257 {
3258         struct osd_thread_info *oti = osd_oti_get(env);
3259         struct osd_object      *obj = osd_dt_obj(dt);
3260         struct osd_thandle     *oh;
3261         struct iam_path_descr  *ipd;
3262         struct iam_container   *bag = &obj->oo_dir->od_container;
3263         int                     rc;
3264
3265         ENTRY;
3266
3267         LINVRNT(osd_invariant(obj));
3268         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3269         LASSERT(bag->ic_object == obj->oo_inode);
3270         LASSERT(handle != NULL);
3271
3272         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
3273                 RETURN(-EACCES);
3274
3275         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3276
3277         ipd = osd_idx_ipd_get(env, bag);
3278         if (unlikely(ipd == NULL))
3279                 RETURN(-ENOMEM);
3280
3281         oh = container_of0(handle, struct osd_thandle, ot_super);
3282         LASSERT(oh->ot_handle != NULL);
3283         LASSERT(oh->ot_handle->h_transaction != NULL);
3284
3285         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3286                 /* swab quota uid/gid provided by caller */
3287                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3288                 key = (const struct dt_key *)&oti->oti_quota_id;
3289         }
3290
3291         rc = iam_delete(oh->ot_handle, bag, (const struct iam_key *)key, ipd);
3292         osd_ipd_put(env, bag, ipd);
3293         LINVRNT(osd_invariant(obj));
3294         RETURN(rc);
3295 }
3296
3297 static int osd_index_declare_ea_delete(const struct lu_env *env,
3298                                        struct dt_object *dt,
3299                                        const struct dt_key *key,
3300                                        struct thandle *handle)
3301 {
3302         struct osd_thandle *oh;
3303         struct inode       *inode;
3304         int                 rc;
3305         ENTRY;
3306
3307         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3308         LASSERT(handle != NULL);
3309
3310         oh = container_of0(handle, struct osd_thandle, ot_super);
3311         LASSERT(oh->ot_handle == NULL);
3312
3313         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3314                              osd_dto_credits_noquota[DTO_INDEX_DELETE]);
3315
3316         inode = osd_dt_obj(dt)->oo_inode;
3317         LASSERT(inode);
3318
3319         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0, oh,
3320                                    true, true, NULL, false);
3321         RETURN(rc);
3322 }
3323
3324 static inline int osd_get_fid_from_dentry(struct ldiskfs_dir_entry_2 *de,
3325                                           struct dt_rec *fid)
3326 {
3327         struct osd_fid_pack *rec;
3328         int                  rc = -ENODATA;
3329
3330         if (de->file_type & LDISKFS_DIRENT_LUFID) {
3331                 rec = (struct osd_fid_pack *) (de->name + de->name_len + 1);
3332                 rc = osd_fid_unpack((struct lu_fid *)fid, rec);
3333         }
3334         return rc;
3335 }
3336
3337 static int osd_mdt_seq_exists(const struct lu_env *env,
3338                               struct osd_device *osd, obd_seq seq)
3339 {
3340         struct lu_seq_range     *range = &osd_oti_get(env)->oti_seq_range;
3341         struct seq_server_site  *ss = osd_seq_site(osd);
3342         int                     rc;
3343         ENTRY;
3344
3345         if (ss == NULL)
3346                 RETURN(1);
3347
3348         /* XXX: currently, each MDT only store avaible sequence on disk, and no
3349          * allocated sequences information on disk, so we have to lookup FLDB,
3350          * but it probably makes more sense also store allocated sequence
3351          * locally, so we do not need do remote FLDB lookup in OSD */
3352         rc = osd_fld_lookup(env, osd, seq, range);
3353         if (rc != 0) {
3354                 CERROR("%s: Can not lookup fld for "LPX64"\n",
3355                        osd_name(osd), seq);
3356                 RETURN(0);
3357         }
3358
3359         RETURN(ss->ss_node_id == range->lsr_index);
3360 }
3361
3362 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
3363                           struct lu_fid *fid)
3364 {
3365         ENTRY;
3366
3367         /* FID seqs not in FLDB, must be local seq */
3368         if (unlikely(!fid_seq_in_fldb(fid_seq(fid))))
3369                 RETURN(0);
3370
3371         /* Currently only check this for FID on MDT */
3372         if (osd_mdt_seq_exists(env, osd, fid_seq(fid)))
3373                 RETURN(0);
3374
3375         RETURN(1);
3376 }
3377
3378 /**
3379  * Index delete function for interoperability mode (b11826).
3380  * It will remove the directory entry added by osd_index_ea_insert().
3381  * This entry is needed to maintain name->fid mapping.
3382  *
3383  * \param key,  key i.e. file entry to be deleted
3384  *
3385  * \retval   0, on success
3386  * \retval -ve, on error
3387  */
3388 static int osd_index_ea_delete(const struct lu_env *env, struct dt_object *dt,
3389                                const struct dt_key *key,
3390                                struct thandle *handle,
3391                                struct lustre_capa *capa)
3392 {
3393         struct osd_object          *obj    = osd_dt_obj(dt);
3394         struct inode               *dir    = obj->oo_inode;
3395         struct dentry              *dentry;
3396         struct osd_thandle         *oh;
3397         struct ldiskfs_dir_entry_2 *de = NULL;
3398         struct buffer_head         *bh;
3399         struct htree_lock          *hlock = NULL;
3400         struct lu_fid              *fid = &osd_oti_get(env)->oti_fid;
3401         struct osd_device          *osd = osd_dev(dt->do_lu.lo_dev);
3402         int                        rc;
3403         ENTRY;
3404
3405         LINVRNT(osd_invariant(obj));
3406         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3407         LASSERT(handle != NULL);
3408
3409         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3410
3411         oh = container_of(handle, struct osd_thandle, ot_super);
3412         LASSERT(oh->ot_handle != NULL);
3413         LASSERT(oh->ot_handle->h_transaction != NULL);
3414
3415         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
3416                 RETURN(-EACCES);
3417
3418         ll_vfs_dq_init(dir);
3419         dentry = osd_child_dentry_get(env, obj,
3420                                       (char *)key, strlen((char *)key));
3421
3422         if (obj->oo_hl_head != NULL) {
3423                 hlock = osd_oti_get(env)->oti_hlock;
3424                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
3425                                    dir, LDISKFS_HLOCK_DEL);
3426         } else {
3427                 down_write(&obj->oo_ext_idx_sem);
3428         }
3429
3430         bh = ldiskfs_find_entry(dir, &dentry->d_name, &de, hlock);
3431         if (bh) {
3432                 __u32 ino = 0;
3433
3434                 /* If this is not the ".." entry, it might be a remote DNE
3435                  * entry and  we need to check if the FID is for a remote
3436                  * MDT.  If the FID is  not in the directory entry (e.g.
3437                  * upgraded 1.8 filesystem without dirdata enabled) then
3438                  * we need to get the FID from the LMA. For a remote directory
3439                  * there HAS to be an LMA, it cannot be an IGIF inode in this
3440                  * case.
3441                  *
3442                  * Delete the entry before the agent inode in order to
3443                  * simplify error handling.  At worst an error after deleting
3444                  * the entry first might leak the agent inode afterward. The
3445                  * reverse would need filesystem abort in case of error deleting
3446                  * the entry after the agent had been removed, or leave a
3447                  * dangling entry pointing at a random inode. */
3448                 if (strcmp((char *)key, dotdot) != 0) {
3449                         LASSERT(de != NULL);
3450                         rc = osd_get_fid_from_dentry(de, (struct dt_rec *)fid);
3451                         /* If Fid is not in dentry, try to get it from LMA */
3452                         if (rc == -ENODATA) {
3453                                 struct osd_inode_id *id;
3454                                 struct inode *inode;
3455
3456                                 /* Before trying to get fid from the inode,
3457                                  * check whether the inode is valid.
3458                                  *
3459                                  * If the inode has been deleted, do not go
3460                                  * ahead to do osd_ea_fid_get, which will set
3461                                  * the inode to bad inode, which might cause
3462                                  * the inode to be deleted uncorrectly */
3463                                 inode = ldiskfs_iget(osd_sb(osd),
3464                                                      le32_to_cpu(de->inode));
3465                                 if (IS_ERR(inode)) {
3466                                         CDEBUG(D_INODE, "%s: "DFID"get inode"
3467                                                "error.\n", osd_name(osd),
3468                                                PFID(fid));
3469                                         rc = PTR_ERR(inode);
3470                                 } else {
3471                                         if (likely(inode->i_nlink != 0)) {
3472                                                 id = &osd_oti_get(env)->oti_id;
3473                                                 rc = osd_ea_fid_get(env, obj,
3474                                                         le32_to_cpu(de->inode),
3475                                                                     fid, id);
3476                                         } else {
3477                                                 CDEBUG(D_INFO, "%s: %u "DFID
3478                                                        "deleted.\n",
3479                                                        osd_name(osd),
3480                                                        le32_to_cpu(de->inode),
3481                                                        PFID(fid));
3482                                                 rc = -ESTALE;
3483                                         }
3484                                         iput(inode);
3485                                 }
3486                         }
3487                         if (rc == 0 &&
3488                             unlikely(osd_remote_fid(env, osd, fid)))
3489                                 /* Need to delete agent inode */
3490                                 ino = le32_to_cpu(de->inode);
3491                 }
3492                 rc = ldiskfs_delete_entry(oh->ot_handle, dir, de, bh);
3493                 brelse(bh);
3494                 if (rc == 0 && unlikely(ino != 0)) {
3495                         rc = osd_delete_local_agent_inode(env, osd, fid, ino,
3496                                                           oh);
3497                         if (rc != 0)
3498                                 CERROR("%s: del local inode "DFID": rc = %d\n",
3499                                        osd_name(osd), PFID(fid), rc);
3500                 }
3501         } else {
3502                 rc = -ENOENT;
3503         }
3504         if (hlock != NULL)
3505                 ldiskfs_htree_unlock(hlock);
3506         else
3507                 up_write(&obj->oo_ext_idx_sem);
3508
3509         if (rc != 0)
3510                 GOTO(out, rc);
3511
3512         /* For inode on the remote MDT, .. will point to
3513          * /Agent directory, Check whether it needs to delete
3514          * from agent directory */
3515         if (unlikely(strcmp((char *)key, dotdot) == 0)) {
3516                 rc = osd_delete_from_remote_parent(env, osd_obj2dev(obj), obj,
3517                                                    oh);
3518                 if (rc != 0 && rc != -ENOENT) {
3519                         CERROR("%s: delete agent inode "DFID": rc = %d\n",
3520                                osd_name(osd), PFID(fid), rc);
3521                 }
3522
3523                 if (rc == -ENOENT)
3524                         rc = 0;
3525
3526                 GOTO(out, rc);
3527         }
3528 out:
3529
3530         LASSERT(osd_invariant(obj));
3531         RETURN(rc);
3532 }
3533
3534 /**
3535  *      Lookup index for \a key and copy record to \a rec.
3536  *
3537  *      \param  dt      osd index object
3538  *      \param  key     key for index
3539  *      \param  rec     record reference
3540  *
3541  *      \retval  +ve  success : exact mach
3542  *      \retval  0    return record with key not greater than \a key
3543  *      \retval -ve   failure
3544  */
3545 static int osd_index_iam_lookup(const struct lu_env *env, struct dt_object *dt,
3546                                 struct dt_rec *rec, const struct dt_key *key,
3547                                 struct lustre_capa *capa)
3548 {
3549         struct osd_object      *obj = osd_dt_obj(dt);
3550         struct iam_path_descr  *ipd;
3551         struct iam_container   *bag = &obj->oo_dir->od_container;
3552         struct osd_thread_info *oti = osd_oti_get(env);
3553         struct iam_iterator    *it = &oti->oti_idx_it;
3554         struct iam_rec         *iam_rec;
3555         int                     rc;
3556
3557         ENTRY;
3558
3559         LASSERT(osd_invariant(obj));
3560         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3561         LASSERT(bag->ic_object == obj->oo_inode);
3562
3563         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
3564                 RETURN(-EACCES);
3565
3566         ipd = osd_idx_ipd_get(env, bag);
3567         if (IS_ERR(ipd))
3568                 RETURN(-ENOMEM);
3569
3570         /* got ipd now we can start iterator. */
3571         iam_it_init(it, bag, 0, ipd);
3572
3573         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3574                 /* swab quota uid/gid provided by caller */
3575                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3576                 key = (const struct dt_key *)&oti->oti_quota_id;
3577         }
3578
3579         rc = iam_it_get(it, (struct iam_key *)key);
3580         if (rc >= 0) {
3581                 if (S_ISDIR(obj->oo_inode->i_mode))
3582                         iam_rec = (struct iam_rec *)oti->oti_ldp;
3583                 else
3584                         iam_rec = (struct iam_rec *) rec;
3585
3586                 iam_reccpy(&it->ii_path.ip_leaf, (struct iam_rec *)iam_rec);
3587
3588                 if (S_ISDIR(obj->oo_inode->i_mode))
3589                         osd_fid_unpack((struct lu_fid *) rec,
3590                                        (struct osd_fid_pack *)iam_rec);
3591                 else if (fid_is_quota(lu_object_fid(&dt->do_lu)))
3592                         osd_quota_unpack(obj, rec);
3593         }
3594
3595         iam_it_put(it);
3596         iam_it_fini(it);
3597         osd_ipd_put(env, bag, ipd);
3598
3599         LINVRNT(osd_invariant(obj));
3600
3601         RETURN(rc);
3602 }
3603
3604 static int osd_index_declare_iam_insert(const struct lu_env *env,
3605                                         struct dt_object *dt,
3606                                         const struct dt_rec *rec,
3607                                         const struct dt_key *key,
3608                                         struct thandle *handle)
3609 {
3610         struct osd_thandle *oh;
3611
3612         LASSERT(handle != NULL);
3613
3614         oh = container_of0(handle, struct osd_thandle, ot_super);
3615         LASSERT(oh->ot_handle == NULL);
3616
3617         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3618                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
3619
3620         return 0;
3621 }
3622
3623 /**
3624  *      Inserts (key, value) pair in \a dt index object.
3625  *
3626  *      \param  dt      osd index object
3627  *      \param  key     key for index
3628  *      \param  rec     record reference
3629  *      \param  th      transaction handler
3630  *
3631  *      \retval  0  success
3632  *      \retval -ve failure
3633  */
3634 static int osd_index_iam_insert(const struct lu_env *env, struct dt_object *dt,
3635                                 const struct dt_rec *rec,
3636                                 const struct dt_key *key, struct thandle *th,
3637                                 struct lustre_capa *capa, int ignore_quota)
3638 {
3639         struct osd_object     *obj = osd_dt_obj(dt);
3640         struct iam_path_descr *ipd;
3641         struct osd_thandle    *oh;
3642         struct iam_container  *bag = &obj->oo_dir->od_container;
3643         struct osd_thread_info *oti = osd_oti_get(env);
3644         struct iam_rec         *iam_rec;
3645         int                     rc;
3646
3647         ENTRY;
3648
3649         LINVRNT(osd_invariant(obj));
3650         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3651         LASSERT(bag->ic_object == obj->oo_inode);
3652         LASSERT(th != NULL);
3653
3654         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
3655                 RETURN(-EACCES);
3656
3657         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3658
3659         ipd = osd_idx_ipd_get(env, bag);
3660         if (unlikely(ipd == NULL))
3661                 RETURN(-ENOMEM);
3662
3663         oh = container_of0(th, struct osd_thandle, ot_super);
3664         LASSERT(oh->ot_handle != NULL);
3665         LASSERT(oh->ot_handle->h_transaction != NULL);
3666         if (S_ISDIR(obj->oo_inode->i_mode)) {
3667                 iam_rec = (struct iam_rec *)oti->oti_ldp;
3668                 osd_fid_pack((struct osd_fid_pack *)iam_rec, rec, &oti->oti_fid);
3669         } else if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3670                 /* pack quota uid/gid */
3671                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3672                 key = (const struct dt_key *)&oti->oti_quota_id;
3673                 /* pack quota record */
3674                 rec = osd_quota_pack(obj, rec, &oti->oti_quota_rec);
3675                 iam_rec = (struct iam_rec *)rec;
3676         } else {
3677                 iam_rec = (struct iam_rec *)rec;
3678         }
3679
3680         rc = iam_insert(oh->ot_handle, bag, (const struct iam_key *)key,
3681                         iam_rec, ipd);
3682         osd_ipd_put(env, bag, ipd);
3683         LINVRNT(osd_invariant(obj));
3684         RETURN(rc);
3685 }
3686
3687 /**
3688  * Calls ldiskfs_add_entry() to add directory entry
3689  * into the directory. This is required for
3690  * interoperability mode (b11826)
3691  *
3692  * \retval   0, on success
3693  * \retval -ve, on error
3694  */
3695 static int __osd_ea_add_rec(struct osd_thread_info *info,
3696                             struct osd_object *pobj, struct inode  *cinode,
3697                             const char *name, const struct dt_rec *fid,
3698                             struct htree_lock *hlock, struct thandle *th)
3699 {
3700         struct ldiskfs_dentry_param *ldp;
3701         struct dentry               *child;
3702         struct osd_thandle          *oth;
3703         int                          rc;
3704
3705         oth = container_of(th, struct osd_thandle, ot_super);
3706         LASSERT(oth->ot_handle != NULL);
3707         LASSERT(oth->ot_handle->h_transaction != NULL);
3708         LASSERT(pobj->oo_inode);
3709
3710         ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
3711         if (unlikely(pobj->oo_inode ==
3712                      osd_sb(osd_obj2dev(pobj))->s_root->d_inode))
3713                 ldp->edp_magic = 0;
3714         else
3715                 osd_get_ldiskfs_dirent_param(ldp, fid);
3716         child = osd_child_dentry_get(info->oti_env, pobj, name, strlen(name));
3717         child->d_fsdata = (void *)ldp;
3718         ll_vfs_dq_init(pobj->oo_inode);
3719         rc = osd_ldiskfs_add_entry(oth->ot_handle, child, cinode, hlock);
3720
3721         RETURN(rc);
3722 }
3723
3724 /**
3725  * Calls ldiskfs_add_dot_dotdot() to add dot and dotdot entries
3726  * into the directory.Also sets flags into osd object to
3727  * indicate dot and dotdot are created. This is required for
3728  * interoperability mode (b11826)
3729  *
3730  * \param dir   directory for dot and dotdot fixup.
3731  * \param obj   child object for linking
3732  *
3733  * \retval   0, on success
3734  * \retval -ve, on error
3735  */
3736 static int osd_add_dot_dotdot(struct osd_thread_info *info,
3737                               struct osd_object *dir,
3738                               struct inode  *parent_dir, const char *name,
3739                               const struct dt_rec *dot_fid,
3740                               const struct dt_rec *dot_dot_fid,
3741                               struct thandle *th)
3742 {
3743         struct inode                *inode = dir->oo_inode;
3744         struct osd_thandle          *oth;
3745         int result = 0;
3746
3747         oth = container_of(th, struct osd_thandle, ot_super);
3748         LASSERT(oth->ot_handle->h_transaction != NULL);
3749         LASSERT(S_ISDIR(dir->oo_inode->i_mode));
3750
3751         if (strcmp(name, dot) == 0) {
3752                 if (dir->oo_compat_dot_created) {
3753                         result = -EEXIST;
3754                 } else {
3755                         LASSERT(inode == parent_dir);
3756                         dir->oo_compat_dot_created = 1;
3757                         result = 0;
3758                 }
3759         } else if (strcmp(name, dotdot) == 0) {
3760                 if (!dir->oo_compat_dot_created)
3761                         return -EINVAL;
3762                 /* in case of rename, dotdot is already created */
3763                 if (dir->oo_compat_dotdot_created) {
3764                         return __osd_ea_add_rec(info, dir, parent_dir, name,
3765                                                 dot_dot_fid, NULL, th);
3766                 }
3767
3768                 result = osd_add_dot_dotdot_internal(info, dir->oo_inode,
3769                                                 parent_dir, dot_fid,
3770                                                 dot_dot_fid, oth);
3771                 if (result == 0)
3772                         dir->oo_compat_dotdot_created = 1;
3773         }
3774
3775         return result;
3776 }
3777
3778
3779 /**
3780  * It will call the appropriate osd_add* function and return the
3781  * value, return by respective functions.
3782  */
3783 static int osd_ea_add_rec(const struct lu_env *env, struct osd_object *pobj,
3784                           struct inode *cinode, const char *name,
3785                           const struct dt_rec *fid, struct thandle *th)
3786 {
3787         struct osd_thread_info *info   = osd_oti_get(env);
3788         struct htree_lock      *hlock;
3789         int                     rc;
3790
3791         hlock = pobj->oo_hl_head != NULL ? info->oti_hlock : NULL;
3792
3793         if (name[0] == '.' && (name[1] == '\0' || (name[1] == '.' &&
3794                                                    name[2] =='\0'))) {
3795                 if (hlock != NULL) {
3796                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
3797                                            pobj->oo_inode, 0);
3798                 } else {
3799                         down_write(&pobj->oo_ext_idx_sem);
3800                 }
3801                 rc = osd_add_dot_dotdot(info, pobj, cinode, name,
3802                      (struct dt_rec *)lu_object_fid(&pobj->oo_dt.do_lu),
3803                                         fid, th);
3804         } else {
3805                 if (hlock != NULL) {
3806                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
3807                                            pobj->oo_inode, LDISKFS_HLOCK_ADD);
3808                 } else {
3809                         down_write(&pobj->oo_ext_idx_sem);
3810                 }
3811
3812                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_INDIR)) {
3813                         struct lu_fid *tfid = &info->oti_fid;
3814
3815                         *tfid = *(const struct lu_fid *)fid;
3816                         tfid->f_ver = ~0;
3817                         rc = __osd_ea_add_rec(info, pobj, cinode, name,
3818                                               (const struct dt_rec *)tfid,
3819                                               hlock, th);
3820                 } else {
3821                         rc = __osd_ea_add_rec(info, pobj, cinode, name, fid,
3822                                               hlock, th);
3823                 }
3824         }
3825         if (hlock != NULL)
3826                 ldiskfs_htree_unlock(hlock);
3827         else
3828                 up_write(&pobj->oo_ext_idx_sem);
3829
3830         return rc;
3831 }
3832
3833 static void
3834 osd_consistency_check(struct osd_thread_info *oti, struct osd_device *dev,
3835                       struct osd_idmap_cache *oic)
3836 {
3837         struct osd_scrub    *scrub = &dev->od_scrub;
3838         struct lu_fid       *fid   = &oic->oic_fid;
3839         struct osd_inode_id *id    = &oti->oti_id;
3840         int                  once  = 0;
3841         int                  rc;
3842         ENTRY;
3843
3844         if (!fid_is_norm(fid) && !fid_is_igif(fid))
3845                 RETURN_EXIT;
3846
3847 again:
3848         rc = osd_oi_lookup(oti, dev, fid, id, OI_CHECK_FLD);
3849         if (rc != 0 && rc != -ENOENT)
3850                 RETURN_EXIT;
3851
3852         if (rc == 0 && osd_id_eq(id, &oic->oic_lid))
3853                 RETURN_EXIT;
3854
3855         if (thread_is_running(&scrub->os_thread)) {
3856                 rc = osd_oii_insert(dev, oic, rc == -ENOENT);
3857                 /* There is race condition between osd_oi_lookup and OI scrub.
3858                  * The OI scrub finished just after osd_oi_lookup() failure.
3859                  * Under such case, it is unnecessary to trigger OI scrub again,
3860                  * but try to call osd_oi_lookup() again. */
3861                 if (unlikely(rc == -EAGAIN))
3862                         goto again;
3863
3864                 RETURN_EXIT;
3865         }
3866
3867         if (!dev->od_noscrub && ++once == 1) {
3868                 CDEBUG(D_LFSCK, "Trigger OI scrub by RPC for "DFID"\n",
3869                        PFID(fid));
3870                 rc = osd_scrub_start(dev);
3871                 LCONSOLE_ERROR("%.16s: trigger OI scrub by RPC for "DFID
3872                                ", rc = %d [2]\n",
3873                                LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name,
3874                                PFID(fid), rc);
3875                 if (rc == 0)
3876                         goto again;
3877         }
3878
3879         EXIT;
3880 }
3881
3882 static int osd_fail_fid_lookup(struct osd_thread_info *oti,
3883                                struct osd_device *dev,
3884                                struct osd_idmap_cache *oic,
3885                                struct lu_fid *fid, __u32 ino)
3886 {
3887         struct lustre_mdt_attrs *lma   = &oti->oti_mdt_attrs;
3888         struct inode            *inode;
3889         int                      rc;
3890
3891         osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
3892         inode = osd_iget(oti, dev, &oic->oic_lid);
3893         if (IS_ERR(inode)) {
3894                 fid_zero(&oic->oic_fid);
3895                 return PTR_ERR(inode);
3896         }
3897
3898         rc = osd_get_lma(oti, inode, &oti->oti_obj_dentry, lma);
3899         iput(inode);
3900         if (rc != 0)
3901                 fid_zero(&oic->oic_fid);
3902         else
3903                 *fid = oic->oic_fid = lma->lma_self_fid;
3904         return rc;
3905 }
3906
3907 int osd_add_oi_cache(struct osd_thread_info *info, struct osd_device *osd,
3908                      struct osd_inode_id *id, const struct lu_fid *fid)
3909 {
3910         CDEBUG(D_INODE, "add "DFID" %u:%u to info %p\n", PFID(fid),
3911                id->oii_ino, id->oii_gen, info);
3912         info->oti_cache.oic_lid = *id;
3913         info->oti_cache.oic_fid = *fid;
3914         info->oti_cache.oic_dev = osd;
3915
3916         return 0;
3917 }
3918
3919 /**
3920  * Calls ->lookup() to find dentry. From dentry get inode and
3921  * read inode's ea to get fid. This is required for  interoperability
3922  * mode (b11826)
3923  *
3924  * \retval   0, on success
3925  * \retval -ve, on error
3926  */
3927 static int osd_ea_lookup_rec(const struct lu_env *env, struct osd_object *obj,
3928                              struct dt_rec *rec, const struct dt_key *key)
3929 {
3930         struct inode               *dir    = obj->oo_inode;
3931         struct dentry              *dentry;
3932         struct ldiskfs_dir_entry_2 *de;
3933         struct buffer_head         *bh;
3934         struct lu_fid              *fid = (struct lu_fid *) rec;
3935         struct htree_lock          *hlock = NULL;
3936         int                         ino;
3937         int                         rc;
3938         ENTRY;
3939
3940         LASSERT(dir->i_op != NULL && dir->i_op->lookup != NULL);
3941
3942         dentry = osd_child_dentry_get(env, obj,
3943                                       (char *)key, strlen((char *)key));
3944
3945         if (obj->oo_hl_head != NULL) {
3946                 hlock = osd_oti_get(env)->oti_hlock;
3947                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
3948                                    dir, LDISKFS_HLOCK_LOOKUP);
3949         } else {
3950                 down_read(&obj->oo_ext_idx_sem);
3951         }
3952
3953         bh = osd_ldiskfs_find_entry(dir, dentry, &de, hlock);
3954         if (bh) {
3955                 struct osd_thread_info *oti = osd_oti_get(env);
3956                 struct osd_inode_id *id = &oti->oti_id;
3957                 struct osd_idmap_cache *oic = &oti->oti_cache;
3958                 struct osd_device *dev = osd_obj2dev(obj);
3959                 struct osd_scrub *scrub = &dev->od_scrub;
3960                 struct scrub_file *sf = &scrub->os_file;
3961
3962                 ino = le32_to_cpu(de->inode);
3963                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP)) {
3964                         brelse(bh);
3965                         rc = osd_fail_fid_lookup(oti, dev, oic, fid, ino);
3966                         GOTO(out, rc);
3967                 }
3968
3969                 rc = osd_get_fid_from_dentry(de, rec);
3970
3971                 /* done with de, release bh */
3972                 brelse(bh);
3973                 if (rc != 0)
3974                         rc = osd_ea_fid_get(env, obj, ino, fid, id);
3975                 else
3976                         osd_id_gen(id, ino, OSD_OII_NOGEN);
3977                 if (rc != 0) {
3978                         fid_zero(&oic->oic_fid);
3979                         GOTO(out, rc);
3980                 }
3981
3982                 rc = osd_add_oi_cache(osd_oti_get(env), osd_obj2dev(obj), id,
3983                                       fid);
3984                 if (rc != 0)
3985                         GOTO(out, rc);
3986                 if ((scrub->os_pos_current <= ino) &&
3987                     ((sf->sf_flags & SF_INCONSISTENT) ||
3988                      (sf->sf_flags & SF_UPGRADE && fid_is_igif(fid)) ||
3989                      ldiskfs_test_bit(osd_oi_fid2idx(dev, fid),
3990                                       sf->sf_oi_bitmap)))
3991                         osd_consistency_check(oti, dev, oic);
3992         } else {
3993                 rc = -ENOENT;
3994         }
3995
3996         GOTO(out, rc);
3997
3998 out:
3999         if (hlock != NULL)
4000                 ldiskfs_htree_unlock(hlock);
4001         else
4002                 up_read(&obj->oo_ext_idx_sem);
4003         return rc;
4004 }
4005
4006 /**
4007  * Find the osd object for given fid.
4008  *
4009  * \param fid need to find the osd object having this fid
4010  *
4011  * \retval osd_object on success
4012  * \retval        -ve on error
4013  */
4014 struct osd_object *osd_object_find(const struct lu_env *env,
4015                                    struct dt_object *dt,
4016                                    const struct lu_fid *fid)
4017 {
4018         struct lu_device  *ludev = dt->do_lu.lo_dev;
4019         struct osd_object *child = NULL;
4020         struct lu_object  *luch;
4021         struct lu_object  *lo;
4022
4023         /*
4024          * at this point topdev might not exist yet
4025          * (i.e. MGS is preparing profiles). so we can
4026          * not rely on topdev and instead lookup with
4027          * our device passed as topdev. this can't work
4028          * if the object isn't cached yet (as osd doesn't
4029          * allocate lu_header). IOW, the object must be
4030          * in the cache, otherwise lu_object_alloc() crashes
4031          * -bzzz
4032          */
4033         luch = lu_object_find_at(env, ludev, fid, NULL);
4034         if (!IS_ERR(luch)) {
4035                 if (lu_object_exists(luch)) {
4036                         lo = lu_object_locate(luch->lo_header, ludev->ld_type);
4037                         if (lo != NULL)
4038                                 child = osd_obj(lo);
4039                         else
4040                                 LU_OBJECT_DEBUG(D_ERROR, env, luch,
4041                                                 "lu_object can't be located"
4042                                                 DFID"\n", PFID(fid));
4043
4044                         if (child == NULL) {
4045                                 lu_object_put(env, luch);
4046                                 CERROR("Unable to get osd_object\n");
4047                                 child = ERR_PTR(-ENOENT);
4048                         }
4049                 } else {
4050                         LU_OBJECT_DEBUG(D_ERROR, env, luch,
4051                                         "lu_object does not exists "DFID"\n",
4052                                         PFID(fid));
4053                         lu_object_put(env, luch);
4054                         child = ERR_PTR(-ENOENT);
4055                 }
4056         } else
4057                 child = (void *)luch;
4058
4059         return child;
4060 }
4061
4062 /**
4063  * Put the osd object once done with it.
4064  *
4065  * \param obj osd object that needs to be put
4066  */
4067 static inline void osd_object_put(const struct lu_env *env,
4068                                   struct osd_object *obj)
4069 {
4070         lu_object_put(env, &obj->oo_dt.do_lu);
4071 }
4072
4073 static int osd_index_declare_ea_insert(const struct lu_env *env,
4074                                        struct dt_object *dt,
4075                                        const struct dt_rec *rec,
4076                                        const struct dt_key *key,
4077                                        struct thandle *handle)
4078 {
4079         struct osd_thandle      *oh;
4080         struct osd_device       *osd   = osd_dev(dt->do_lu.lo_dev);
4081         struct lu_fid           *fid = (struct lu_fid *)rec;
4082         int                     rc;
4083         ENTRY;
4084
4085         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
4086         LASSERT(handle != NULL);
4087
4088         oh = container_of0(handle, struct osd_thandle, ot_super);
4089         LASSERT(oh->ot_handle == NULL);
4090
4091         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4092                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
4093
4094         if (osd_dt_obj(dt)->oo_inode == NULL) {
4095                 const char *name  = (const char *)key;
4096                 /* Object is not being created yet. Only happens when
4097                  *     1. declare directory create
4098                  *     2. declare insert .
4099                  *     3. declare insert ..
4100                  */
4101                 LASSERT(strcmp(name, dotdot) == 0 || strcmp(name, dot) == 0);
4102         } else {
4103                 struct inode *inode = osd_dt_obj(dt)->oo_inode;
4104
4105                 /* We ignore block quota on meta pool (MDTs), so needn't
4106                  * calculate how many blocks will be consumed by this index
4107                  * insert */
4108                 rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0,
4109                                            oh, true, true, NULL, false);
4110         }
4111
4112         if (fid == NULL)
4113                 RETURN(0);
4114
4115         rc = osd_remote_fid(env, osd, fid);
4116         if (rc <= 0)
4117                 RETURN(rc);
4118
4119         rc = 0;
4120
4121         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
4122                              osd_dto_credits_noquota[DTO_OBJECT_CREATE]);
4123         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4124                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
4125         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4126                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
4127
4128         RETURN(rc);
4129 }
4130
4131 /**
4132  * Index add function for interoperability mode (b11826).
4133  * It will add the directory entry.This entry is needed to
4134  * maintain name->fid mapping.
4135  *
4136  * \param key it is key i.e. file entry to be inserted
4137  * \param rec it is value of given key i.e. fid
4138  *
4139  * \retval   0, on success
4140  * \retval -ve, on error
4141  */
4142 static int osd_index_ea_insert(const struct lu_env *env, struct dt_object *dt,
4143                                const struct dt_rec *rec,
4144                                const struct dt_key *key, struct thandle *th,
4145                                struct lustre_capa *capa, int ignore_quota)
4146 {
4147         struct osd_object       *obj = osd_dt_obj(dt);
4148         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
4149         struct lu_fid           *fid = (struct lu_fid *) rec;
4150         const char              *name = (const char *)key;
4151         struct osd_thread_info  *oti   = osd_oti_get(env);
4152         struct osd_inode_id     *id    = &oti->oti_id;
4153         struct inode            *child_inode = NULL;
4154         struct osd_object       *child = NULL;
4155         int                     rc;
4156         ENTRY;
4157
4158         LASSERT(osd_invariant(obj));
4159         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
4160         LASSERT(th != NULL);
4161
4162         osd_trans_exec_op(env, th, OSD_OT_INSERT);
4163
4164         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
4165                 RETURN(-EACCES);
4166
4167         LASSERTF(fid_is_sane(fid), "fid"DFID" is insane!", PFID(fid));
4168
4169         rc = osd_remote_fid(env, osd, fid);
4170         if (rc < 0) {
4171                 CERROR("%s: Can not find object "DFID" rc %d\n",
4172                        osd_name(osd), PFID(fid), rc);
4173                 RETURN(rc);
4174         }
4175
4176         if (rc == 1) {
4177                 /* Insert remote entry */
4178                 if (strcmp(name, dotdot) == 0 && strlen(name) == 2) {
4179                         struct osd_mdobj_map    *omm = osd->od_mdt_map;
4180                         struct osd_thandle      *oh;
4181
4182                         /* If parent on remote MDT, we need put this object
4183                          * under AGENT */
4184                         oh = container_of(th, typeof(*oh), ot_super);
4185                         rc = osd_add_to_remote_parent(env, osd, obj, oh);
4186                         if (rc != 0) {
4187                                 CERROR("%s: add "DFID" error: rc = %d\n",
4188                                        osd_name(osd),
4189                                        PFID(lu_object_fid(&dt->do_lu)), rc);
4190                                 RETURN(rc);
4191                         }
4192
4193                         child_inode = igrab(omm->omm_remote_parent->d_inode);
4194                 } else {
4195                         child_inode = osd_create_local_agent_inode(env, osd,
4196                                                                    obj, fid,
4197                                                                    th);
4198                         if (IS_ERR(child_inode))
4199                                 RETURN(PTR_ERR(child_inode));
4200                 }
4201         } else {
4202                 /* Insert local entry */
4203                 child = osd_object_find(env, dt, fid);
4204                 if (IS_ERR(child)) {
4205                         CERROR("%s: Can not find object "DFID"%u:%u: rc = %d\n",
4206                                osd_name(osd), PFID(fid),
4207                                id->oii_ino, id->oii_gen,
4208                                (int)PTR_ERR(child_inode));
4209                         RETURN(PTR_ERR(child_inode));
4210                 }
4211                 child_inode = igrab(child->oo_inode);
4212         }
4213
4214         rc = osd_ea_add_rec(env, obj, child_inode, name, rec, th);
4215
4216         iput(child_inode);
4217         if (child != NULL)
4218                 osd_object_put(env, child);
4219         LASSERT(osd_invariant(obj));
4220         RETURN(rc);
4221 }
4222
4223 /**
4224  *  Initialize osd Iterator for given osd index object.
4225  *
4226  *  \param  dt      osd index object
4227  */
4228
4229 static struct dt_it *osd_it_iam_init(const struct lu_env *env,
4230                                      struct dt_object *dt,
4231                                      __u32 unused,
4232                                      struct lustre_capa *capa)
4233 {
4234         struct osd_it_iam      *it;
4235         struct osd_thread_info *oti = osd_oti_get(env);
4236         struct osd_object      *obj = osd_dt_obj(dt);
4237         struct lu_object       *lo  = &dt->do_lu;
4238         struct iam_path_descr  *ipd;
4239         struct iam_container   *bag = &obj->oo_dir->od_container;
4240
4241         LASSERT(lu_object_exists(lo));
4242
4243         if (osd_object_auth(env, dt, capa, CAPA_OPC_BODY_READ))
4244                 return ERR_PTR(-EACCES);
4245
4246         it = &oti->oti_it;
4247         ipd = osd_it_ipd_get(env, bag);
4248         if (likely(ipd != NULL)) {
4249                 it->oi_obj = obj;
4250                 it->oi_ipd = ipd;
4251                 lu_object_get(lo);
4252                 iam_it_init(&it->oi_it, bag, IAM_IT_MOVE, ipd);
4253                 return (struct dt_it *)it;
4254         }
4255         return ERR_PTR(-ENOMEM);
4256 }
4257
4258 /**
4259  * free given Iterator.
4260  */
4261
4262 static void osd_it_iam_fini(const struct lu_env *env, struct dt_it *di)
4263 {
4264         struct osd_it_iam *it = (struct osd_it_iam *)di;
4265         struct osd_object *obj = it->oi_obj;
4266
4267         iam_it_fini(&it->oi_it);
4268         osd_ipd_put(env, &obj->oo_dir->od_container, it->oi_ipd);
4269         lu_object_put(env, &obj->oo_dt.do_lu);
4270 }
4271
4272 /**
4273  *  Move Iterator to record specified by \a key
4274  *
4275  *  \param  di      osd iterator
4276  *  \param  key     key for index
4277  *
4278  *  \retval +ve  di points to record with least key not larger than key
4279  *  \retval  0   di points to exact matched key
4280  *  \retval -ve  failure
4281  */
4282
4283 static int osd_it_iam_get(const struct lu_env *env,
4284                           struct dt_it *di, const struct dt_key *key)
4285 {
4286         struct osd_thread_info  *oti = osd_oti_get(env);
4287         struct osd_it_iam       *it = (struct osd_it_iam *)di;
4288
4289         if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
4290                 /* swab quota uid/gid */
4291                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
4292                 key = (struct dt_key *)&oti->oti_quota_id;
4293         }
4294
4295         return iam_it_get(&it->oi_it, (const struct iam_key *)key);
4296 }
4297
4298 /**
4299  *  Release Iterator
4300  *
4301  *  \param  di      osd iterator
4302  */
4303 static void osd_it_iam_put(const struct lu_env *env, struct dt_it *di)
4304 {
4305         struct osd_it_iam *it = (struct osd_it_iam *)di;
4306
4307         iam_it_put(&it->oi_it);
4308 }
4309
4310 /**
4311  *  Move iterator by one record
4312  *
4313  *  \param  di      osd iterator
4314  *
4315  *  \retval +1   end of container reached
4316  *  \retval  0   success
4317  *  \retval -ve  failure
4318  */
4319
4320 static int osd_it_iam_next(const struct lu_env *env, struct dt_it *di)
4321 {
4322         struct osd_it_iam *it = (struct osd_it_iam *)di;
4323
4324         return iam_it_next(&it->oi_it);
4325 }
4326
4327 /**
4328  * Return pointer to the key under iterator.
4329  */
4330
4331 static struct dt_key *osd_it_iam_key(const struct lu_env *env,
4332                                  const struct dt_it *di)
4333 {
4334         struct osd_thread_info *oti = osd_oti_get(env);
4335         struct osd_it_iam      *it = (struct osd_it_iam *)di;
4336         struct osd_object      *obj = it->oi_obj;
4337         struct dt_key          *key;
4338
4339         key = (struct dt_key *)iam_it_key_get(&it->oi_it);
4340
4341         if (!IS_ERR(key) && fid_is_quota(lu_object_fid(&obj->oo_dt.do_lu))) {
4342                 /* swab quota uid/gid */
4343                 oti->oti_quota_id = le64_to_cpu(*((__u64 *)key));
4344                 key = (struct dt_key *)&oti->oti_quota_id;
4345         }
4346
4347         return key;
4348 }
4349
4350 /**
4351  * Return size of key under iterator (in bytes)
4352  */
4353
4354 static int osd_it_iam_key_size(const struct lu_env *env, const struct dt_it *di)
4355 {
4356         struct osd_it_iam *it = (struct osd_it_iam *)di;
4357
4358         return iam_it_key_size(&it->oi_it);
4359 }
4360
4361 static inline void
4362 osd_it_append_attrs(struct lu_dirent *ent, int len, __u16 type)
4363 {
4364         /* check if file type is required */
4365         if (ent->lde_attrs & LUDA_TYPE) {
4366                 struct luda_type *lt;
4367                 int align = sizeof(*lt) - 1;
4368
4369                 len = (len + align) & ~align;
4370                 lt = (struct luda_type *)(ent->lde_name + len);
4371                 lt->lt_type = cpu_to_le16(DTTOIF(type));
4372         }
4373
4374         ent->lde_attrs = cpu_to_le32(ent->lde_attrs);
4375 }
4376
4377 /**
4378  * build lu direct from backend fs dirent.
4379  */
4380
4381 static inline void
4382 osd_it_pack_dirent(struct lu_dirent *ent, struct lu_fid *fid, __u64 offset,
4383                    char *name, __u16 namelen, __u16 type, __u32 attr)
4384 {
4385         ent->lde_attrs = attr | LUDA_FID;
4386         fid_cpu_to_le(&ent->lde_fid, fid);
4387
4388         ent->lde_hash = cpu_to_le64(offset);
4389         ent->lde_reclen = cpu_to_le16(lu_dirent_calc_size(namelen, attr));
4390
4391         strncpy(ent->lde_name, name, namelen);
4392         ent->lde_name[namelen] = '\0';
4393         ent->lde_namelen = cpu_to_le16(namelen);
4394
4395         /* append lustre attributes */
4396         osd_it_append_attrs(ent, namelen, type);
4397 }
4398
4399 /**
4400  * Return pointer to the record under iterator.
4401  */
4402 static int osd_it_iam_rec(const struct lu_env *env,
4403                           const struct dt_it *di,
4404                           struct dt_rec *dtrec, __u32 attr)
4405 {
4406         struct osd_it_iam      *it   = (struct osd_it_iam *)di;
4407         struct osd_thread_info *info = osd_oti_get(env);
4408         ENTRY;
4409
4410         if (S_ISDIR(it->oi_obj->oo_inode->i_mode)) {
4411                 const struct osd_fid_pack *rec;
4412                 struct lu_fid             *fid = &info->oti_fid;
4413                 struct lu_dirent          *lde = (struct lu_dirent *)dtrec;
4414                 char                      *name;
4415                 int                        namelen;
4416                 __u64                      hash;
4417                 int                        rc;
4418
4419                 name = (char *)iam_it_key_get(&it->oi_it);
4420                 if (IS_ERR(name))
4421                         RETURN(PTR_ERR(name));
4422
4423                 namelen = iam_it_key_size(&it->oi_it);
4424
4425                 rec = (const struct osd_fid_pack *)iam_it_rec_get(&it->oi_it);
4426                 if (IS_ERR(rec))
4427                         RETURN(PTR_ERR(rec));
4428
4429                 rc = osd_fid_unpack(fid, rec);
4430                 if (rc)
4431                         RETURN(rc);
4432
4433                 hash = iam_it_store(&it->oi_it);
4434
4435                 /* IAM does not store object type in IAM index (dir) */
4436                 osd_it_pack_dirent(lde, fid, hash, name, namelen,
4437                                    0, LUDA_FID);
4438         } else if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
4439                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
4440                            (struct iam_rec *)dtrec);
4441                 osd_quota_unpack(it->oi_obj, dtrec);
4442         } else {
4443                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
4444                            (struct iam_rec *)dtrec);
4445         }
4446
4447         RETURN(0);
4448 }
4449
4450 /**
4451  * Returns cookie for current Iterator position.
4452  */
4453 static __u64 osd_it_iam_store(const struct lu_env *env, const struct dt_it *di)
4454 {
4455         struct osd_it_iam *it = (struct osd_it_iam *)di;
4456
4457         return iam_it_store(&it->oi_it);
4458 }
4459
4460 /**
4461  * Restore iterator from cookie.
4462  *
4463  * \param  di      osd iterator
4464  * \param  hash    Iterator location cookie
4465  *
4466  * \retval +ve  di points to record with least key not larger than key.
4467  * \retval  0   di points to exact matched key
4468  * \retval -ve  failure
4469  */
4470
4471 static int osd_it_iam_load(const struct lu_env *env,
4472                            const struct dt_it *di, __u64 hash)
4473 {
4474         struct osd_it_iam *it = (struct osd_it_iam *)di;
4475
4476         return iam_it_load(&it->oi_it, hash);
4477 }
4478
4479 static const struct dt_index_operations osd_index_iam_ops = {
4480         .dio_lookup         = osd_index_iam_lookup,
4481         .dio_declare_insert = osd_index_declare_iam_insert,
4482         .dio_insert         = osd_index_iam_insert,
4483         .dio_declare_delete = osd_index_declare_iam_delete,
4484         .dio_delete         = osd_index_iam_delete,
4485         .dio_it     = {
4486                 .init     = osd_it_iam_init,
4487                 .fini     = osd_it_iam_fini,
4488                 .get      = osd_it_iam_get,
4489                 .put      = osd_it_iam_put,
4490                 .next     = osd_it_iam_next,
4491                 .key      = osd_it_iam_key,
4492                 .key_size = osd_it_iam_key_size,
4493                 .rec      = osd_it_iam_rec,
4494                 .store    = osd_it_iam_store,
4495                 .load     = osd_it_iam_load
4496         }
4497 };
4498
4499
4500 /**
4501  * Creates or initializes iterator context.
4502  *
4503  * \retval struct osd_it_ea, iterator structure on success
4504  *
4505  */
4506 static struct dt_it *osd_it_ea_init(const struct lu_env *env,
4507                                     struct dt_object *dt,
4508                                     __u32 attr,
4509                                     struct lustre_capa *capa)
4510 {
4511         struct osd_object       *obj  = osd_dt_obj(dt);
4512         struct osd_thread_info  *info = osd_oti_get(env);
4513         struct osd_it_ea        *it   = &info->oti_it_ea;
4514         struct file             *file = &it->oie_file;
4515         struct lu_object        *lo   = &dt->do_lu;
4516         struct dentry           *obj_dentry = &info->oti_it_dentry;
4517         ENTRY;
4518         LASSERT(lu_object_exists(lo));
4519
4520         obj_dentry->d_inode = obj->oo_inode;
4521         obj_dentry->d_sb = osd_sb(osd_obj2dev(obj));
4522         obj_dentry->d_name.hash = 0;
4523
4524         it->oie_rd_dirent       = 0;
4525         it->oie_it_dirent       = 0;
4526         it->oie_dirent          = NULL;
4527         it->oie_buf             = info->oti_it_ea_buf;
4528         it->oie_obj             = obj;
4529
4530         /* Reset the "file" totally to avoid to reuse any old value from
4531          * former readdir handling, the "file->f_pos" should be zero. */
4532         memset(file, 0, sizeof(*file));
4533         /* Only FMODE_64BITHASH or FMODE_32BITHASH should be set, NOT both. */
4534         if (attr & LUDA_64BITHASH)
4535                 file->f_mode    = FMODE_64BITHASH;
4536         else
4537                 file->f_mode    = FMODE_32BITHASH;
4538         file->f_dentry          = obj_dentry;
4539         file->f_mapping         = obj->oo_inode->i_mapping;
4540         file->f_op              = obj->oo_inode->i_fop;
4541         lu_object_get(lo);
4542         RETURN((struct dt_it *) it);
4543 }
4544
4545 /**
4546  * Destroy or finishes iterator context.
4547  *
4548  * \param di iterator structure to be destroyed
4549  */
4550 static void osd_it_ea_fini(const struct lu_env *env, struct dt_it *di)
4551 {
4552         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
4553         struct osd_object    *obj  = it->oie_obj;
4554         struct inode       *inode  = obj->oo_inode;
4555
4556         ENTRY;
4557         it->oie_file.f_op->release(inode, &it->oie_file);
4558         lu_object_put(env, &obj->oo_dt.do_lu);
4559         EXIT;
4560 }
4561
4562 /**
4563  * It position the iterator at given key, so that next lookup continues from
4564  * that key Or it is similar to dio_it->load() but based on a key,
4565  * rather than file position.
4566  *
4567  * As a special convention, osd_it_ea_get(env, di, "") has to rewind iterator
4568  * to the beginning.
4569  *
4570  * TODO: Presently return +1 considering it is only used by mdd_dir_is_empty().
4571  */
4572 static int osd_it_ea_get(const struct lu_env *env,
4573                          struct dt_it *di, const struct dt_key *key)
4574 {
4575         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
4576
4577         ENTRY;
4578         LASSERT(((const char *)key)[0] == '\0');
4579         it->oie_file.f_pos      = 0;
4580         it->oie_rd_dirent       = 0;
4581         it->oie_it_dirent       = 0;
4582         it->oie_dirent          = NULL;
4583
4584         RETURN(+1);
4585 }
4586
4587 /**
4588  * Does nothing
4589  */
4590 static void osd_it_ea_put(const struct lu_env *env, struct dt_it *di)
4591 {
4592 }
4593
4594 /**
4595  * It is called internally by ->readdir(). It fills the
4596  * iterator's in-memory data structure with required
4597  * information i.e. name, namelen, rec_size etc.
4598  *
4599  * \param buf in which information to be filled in.
4600  * \param name name of the file in given dir
4601  *
4602  * \retval 0 on success
4603  * \retval 1 on buffer full
4604  */
4605 static int osd_ldiskfs_filldir(char *buf, const char *name, int namelen,
4606                                loff_t offset, __u64 ino,
4607                                unsigned d_type)
4608 {
4609         struct osd_it_ea        *it   = (struct osd_it_ea *)buf;
4610         struct osd_object       *obj  = it->oie_obj;
4611         struct osd_it_ea_dirent *ent  = it->oie_dirent;
4612         struct lu_fid           *fid  = &ent->oied_fid;
4613         struct osd_fid_pack     *rec;
4614         ENTRY;
4615
4616         /* this should never happen */
4617         if (unlikely(namelen == 0 || namelen > LDISKFS_NAME_LEN)) {
4618                 CERROR("ldiskfs return invalid namelen %d\n", namelen);
4619                 RETURN(-EIO);
4620         }
4621
4622         if ((void *) ent - it->oie_buf + sizeof(*ent) + namelen >
4623             OSD_IT_EA_BUFSIZE)
4624                 RETURN(1);
4625
4626         /* "." is just the object itself. */
4627         if (namelen == 1 && name[0] == '.') {
4628                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
4629         } else if (d_type & LDISKFS_DIRENT_LUFID) {
4630                 rec = (struct osd_fid_pack*) (name + namelen + 1);
4631                 if (osd_fid_unpack(fid, rec) != 0)
4632                         fid_zero(fid);
4633         } else {
4634                 fid_zero(fid);
4635         }
4636         d_type &= ~LDISKFS_DIRENT_LUFID;
4637
4638         /* NOT export local root. */
4639         if (unlikely(osd_sb(osd_obj2dev(obj))->s_root->d_inode->i_ino == ino)) {
4640                 ino = obj->oo_inode->i_ino;
4641                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
4642         }
4643
4644         ent->oied_ino     = ino;
4645         ent->oied_off     = offset;
4646         ent->oied_namelen = namelen;
4647         ent->oied_type    = d_type;
4648
4649         memcpy(ent->oied_name, name, namelen);
4650
4651         it->oie_rd_dirent++;
4652         it->oie_dirent = (void *) ent + cfs_size_round(sizeof(*ent) + namelen);
4653         RETURN(0);
4654 }
4655
4656 /**
4657  * Calls ->readdir() to load a directory entry at a time
4658  * and stored it in iterator's in-memory data structure.
4659  *
4660  * \param di iterator's in memory structure
4661  *
4662  * \retval   0 on success
4663  * \retval -ve on error
4664  */
4665 static int osd_ldiskfs_it_fill(const struct lu_env *env,
4666                                const struct dt_it *di)
4667 {
4668         struct osd_it_ea   *it    = (struct osd_it_ea *)di;
4669         struct osd_object  *obj   = it->oie_obj;
4670         struct inode       *inode = obj->oo_inode;
4671         struct htree_lock  *hlock = NULL;
4672         int                 result = 0;
4673
4674         ENTRY;
4675         it->oie_dirent = it->oie_buf;
4676         it->oie_rd_dirent = 0;
4677
4678         if (obj->oo_hl_head != NULL) {
4679                 hlock = osd_oti_get(env)->oti_hlock;
4680                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
4681                                    inode, LDISKFS_HLOCK_READDIR);
4682         } else {
4683                 down_read(&obj->oo_ext_idx_sem);
4684         }
4685
4686         result = inode->i_fop->readdir(&it->oie_file, it,
4687                                        (filldir_t) osd_ldiskfs_filldir);
4688
4689         if (hlock != NULL)
4690                 ldiskfs_htree_unlock(hlock);
4691         else
4692                 up_read(&obj->oo_ext_idx_sem);
4693
4694         if (it->oie_rd_dirent == 0) {
4695                 result = -EIO;
4696         } else {
4697                 it->oie_dirent = it->oie_buf;
4698                 it->oie_it_dirent = 1;
4699         }
4700
4701         RETURN(result);
4702 }
4703
4704 /**
4705  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
4706  * to load a directory entry at a time and stored it in
4707  * iterator's in-memory data structure.
4708  *
4709  * \param di iterator's in memory structure
4710  *
4711  * \retval +ve iterator reached to end
4712  * \retval   0 iterator not reached to end
4713  * \retval -ve on error
4714  */
4715 static int osd_it_ea_next(const struct lu_env *env, struct dt_it *di)
4716 {
4717         struct osd_it_ea *it = (struct osd_it_ea *)di;
4718         int rc;
4719
4720         ENTRY;
4721
4722         if (it->oie_it_dirent < it->oie_rd_dirent) {
4723                 it->oie_dirent =
4724                         (void *) it->oie_dirent +
4725                         cfs_size_round(sizeof(struct osd_it_ea_dirent) +
4726                                        it->oie_dirent->oied_namelen);
4727                 it->oie_it_dirent++;
4728                 RETURN(0);
4729         } else {
4730                 if (it->oie_file.f_pos == ldiskfs_get_htree_eof(&it->oie_file))
4731                         rc = +1;
4732                 else
4733                         rc = osd_ldiskfs_it_fill(env, di);
4734         }
4735
4736         RETURN(rc);
4737 }
4738
4739 /**
4740  * Returns the key at current position from iterator's in memory structure.
4741  *
4742  * \param di iterator's in memory structure
4743  *
4744  * \retval key i.e. struct dt_key on success
4745  */
4746 static struct dt_key *osd_it_ea_key(const struct lu_env *env,
4747                                     const struct dt_it *di)
4748 {
4749         struct osd_it_ea *it = (struct osd_it_ea *)di;
4750
4751         return (struct dt_key *)it->oie_dirent->oied_name;
4752 }
4753
4754 /**
4755  * Returns the key's size at current position from iterator's in memory structure.
4756  *
4757  * \param di iterator's in memory structure
4758  *
4759  * \retval key_size i.e. struct dt_key on success
4760  */
4761 static int osd_it_ea_key_size(const struct lu_env *env, const struct dt_it *di)
4762 {
4763         struct osd_it_ea *it = (struct osd_it_ea *)di;
4764
4765         return it->oie_dirent->oied_namelen;
4766 }
4767
4768 static int
4769 osd_dirent_update(handle_t *jh, struct super_block *sb,
4770                   struct osd_it_ea_dirent *ent, struct lu_fid *fid,
4771                   struct buffer_head *bh, struct ldiskfs_dir_entry_2 *de)
4772 {
4773         struct osd_fid_pack *rec;
4774         int                  rc;
4775         ENTRY;
4776
4777         LASSERT(de->file_type & LDISKFS_DIRENT_LUFID);
4778         LASSERT(de->rec_len >= de->name_len + sizeof(struct osd_fid_pack));
4779
4780         rc = ldiskfs_journal_get_write_access(jh, bh);
4781         if (rc != 0) {
4782                 CERROR("%.16s: fail to write access 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                 RETURN(rc);
4787         }
4788
4789         rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
4790         fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
4791         rc = ldiskfs_journal_dirty_metadata(jh, bh);
4792         if (rc != 0)
4793                 CERROR("%.16s: fail to dirty metadata for update dirent: "
4794                        "name = %.*s, rc = %d\n",
4795                        LDISKFS_SB(sb)->s_es->s_volume_name,
4796                        ent->oied_namelen, ent->oied_name, rc);
4797
4798         RETURN(rc);
4799 }
4800
4801 static inline int
4802 osd_dirent_has_space(__u16 reclen, __u16 namelen, unsigned blocksize)
4803 {
4804         if (ldiskfs_rec_len_from_disk(reclen, blocksize) >=
4805             __LDISKFS_DIR_REC_LEN(namelen + 1 + sizeof(struct osd_fid_pack)))
4806                 return 1;
4807         else
4808                 return 0;
4809 }
4810
4811 static inline int
4812 osd_dot_dotdot_has_space(struct ldiskfs_dir_entry_2 *de, int dot_dotdot)
4813 {
4814         LASSERTF(dot_dotdot == 1 || dot_dotdot == 2,
4815                  "dot_dotdot = %d\n", dot_dotdot);
4816
4817         if (LDISKFS_DIR_REC_LEN(de) >=
4818             __LDISKFS_DIR_REC_LEN(dot_dotdot + 1 + sizeof(struct osd_fid_pack)))
4819                 return 1;
4820         else
4821                 return 0;
4822 }
4823
4824 static int
4825 osd_dirent_reinsert(const struct lu_env *env, handle_t *jh,
4826                     struct inode *dir, struct inode *inode,
4827                     struct osd_it_ea_dirent *ent, struct lu_fid *fid,
4828                     struct buffer_head *bh, struct ldiskfs_dir_entry_2 *de,
4829                     struct htree_lock *hlock)
4830 {
4831         struct dentry               *dentry;
4832         struct osd_fid_pack         *rec;
4833         struct ldiskfs_dentry_param *ldp;
4834         int                          rc;
4835         ENTRY;
4836
4837         if (!LDISKFS_HAS_INCOMPAT_FEATURE(inode->i_sb,
4838                                           LDISKFS_FEATURE_INCOMPAT_DIRDATA))
4839                 RETURN(0);
4840
4841         /* There is enough space to hold the FID-in-dirent. */
4842         if (osd_dirent_has_space(de->rec_len, ent->oied_namelen,
4843                                  dir->i_sb->s_blocksize)) {
4844                 rc = ldiskfs_journal_get_write_access(jh, bh);
4845                 if (rc != 0) {
4846                         CERROR("%.16s: fail to write access for reinsert "
4847                                "dirent: name = %.*s, rc = %d\n",
4848                                LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4849                                ent->oied_namelen, ent->oied_name, rc);
4850                         RETURN(rc);
4851                 }
4852
4853                 de->name[de->name_len] = 0;
4854                 rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
4855                 rec->fp_len = sizeof(struct lu_fid) + 1;
4856                 fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
4857                 de->file_type |= LDISKFS_DIRENT_LUFID;
4858
4859                 rc = ldiskfs_journal_dirty_metadata(jh, bh);
4860                 if (rc != 0)
4861                         CERROR("%.16s: fail to dirty metadata for reinsert "
4862                                "dirent: name = %.*s, rc = %d\n",
4863                                LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4864                                ent->oied_namelen, ent->oied_name, rc);
4865
4866                 RETURN(rc);
4867         }
4868
4869         rc = ldiskfs_delete_entry(jh, dir, de, bh);
4870         if (rc != 0) {
4871                 CERROR("%.16s: fail to delete entry for reinsert dirent: "
4872                        "name = %.*s, rc = %d\n",
4873                        LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4874                        ent->oied_namelen, ent->oied_name, rc);
4875                 RETURN(rc);
4876         }
4877
4878         dentry = osd_child_dentry_by_inode(env, dir, ent->oied_name,
4879                                            ent->oied_namelen);
4880         ldp = (struct ldiskfs_dentry_param *)osd_oti_get(env)->oti_ldp;
4881         osd_get_ldiskfs_dirent_param(ldp, (const struct dt_rec *)fid);
4882         dentry->d_fsdata = (void *)ldp;
4883         ll_vfs_dq_init(dir);
4884         rc = osd_ldiskfs_add_entry(jh, dentry, inode, hlock);
4885         /* It is too bad, we cannot reinsert the name entry back.
4886          * That means we lose it! */
4887         if (rc != 0)
4888                 CERROR("%.16s: fail to insert entry for reinsert dirent: "
4889                        "name = %.*s, rc = %d\n",
4890                        LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4891                        ent->oied_namelen, ent->oied_name, rc);
4892
4893         RETURN(rc);
4894 }
4895
4896 static int
4897 osd_dirent_check_repair(const struct lu_env *env, struct osd_object *obj,
4898                         struct osd_it_ea *it, struct lu_fid *fid,
4899                         struct osd_inode_id *id, __u32 *attr)
4900 {
4901         struct osd_thread_info     *info        = osd_oti_get(env);
4902         struct lustre_mdt_attrs    *lma         = &info->oti_mdt_attrs;
4903         struct osd_device          *dev         = osd_obj2dev(obj);
4904         struct super_block         *sb          = osd_sb(dev);
4905         const char                 *devname     =
4906                                         LDISKFS_SB(sb)->s_es->s_volume_name;
4907         struct osd_it_ea_dirent    *ent         = it->oie_dirent;
4908         struct inode               *dir         = obj->oo_inode;
4909         struct htree_lock          *hlock       = NULL;
4910         struct buffer_head         *bh          = NULL;
4911         handle_t                   *jh          = NULL;
4912         struct ldiskfs_dir_entry_2 *de;
4913         struct dentry              *dentry;
4914         struct inode               *inode;
4915         int                         credits;
4916         int                         rc;
4917         int                         dot_dotdot  = 0;
4918         bool                        dirty       = false;
4919         ENTRY;
4920
4921         if (ent->oied_name[0] == '.') {
4922                 if (ent->oied_namelen == 1)
4923                         dot_dotdot = 1;
4924                 else if (ent->oied_namelen == 2 && ent->oied_name[1] == '.')
4925                         dot_dotdot = 2;
4926         }
4927
4928         dentry = osd_child_dentry_get(env, obj, ent->oied_name,
4929                                       ent->oied_namelen);
4930
4931         /* We need to ensure that the name entry is still valid.
4932          * Because it may be removed or renamed by other already.
4933          *
4934          * The unlink or rename operation will start journal before PDO lock,
4935          * so to avoid deadlock, here we need to start journal handle before
4936          * related PDO lock also. But because we do not know whether there
4937          * will be something to be repaired before PDO lock, we just start
4938          * journal without conditions.
4939          *
4940          * We may need to remove the name entry firstly, then insert back.
4941          * One credit is for user quota file update.
4942          * One credit is for group quota file update.
4943          * Two credits are for dirty inode. */
4944         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE] +
4945                   osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1 + 1 + 2;
4946
4947 again:
4948         if (dev->od_dirent_journal) {
4949                 jh = ldiskfs_journal_start_sb(sb, credits);
4950                 if (IS_ERR(jh)) {
4951                         rc = PTR_ERR(jh);
4952                         CERROR("%.16s: fail to start trans for dirent "
4953                                "check_repair: credits %d, name %.*s, rc %d\n",
4954                                devname, credits, ent->oied_namelen,
4955                                ent->oied_name, rc);
4956                         RETURN(rc);
4957                 }
4958
4959                 if (obj->oo_hl_head != NULL) {
4960                         hlock = osd_oti_get(env)->oti_hlock;
4961                         /* "0" means exclusive lock for the whole directory.
4962                          * We need to prevent others access such name entry
4963                          * during the delete + insert. Neither HLOCK_ADD nor
4964                          * HLOCK_DEL cannot guarantee the atomicity. */
4965                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir, 0);
4966                 } else {
4967                         down_write(&obj->oo_ext_idx_sem);
4968                 }
4969         } else {
4970                 if (obj->oo_hl_head != NULL) {
4971                         hlock = osd_oti_get(env)->oti_hlock;
4972                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir,
4973                                            LDISKFS_HLOCK_LOOKUP);
4974                 } else {
4975                         down_read(&obj->oo_ext_idx_sem);
4976                 }
4977         }
4978
4979         bh = osd_ldiskfs_find_entry(dir, dentry, &de, hlock);
4980         /* For dot/dotdot entry, if there is not enough space to hold the
4981          * FID-in-dirent, just keep them there. It only happens when the
4982          * device upgraded from 1.8 or restored from MDT file-level backup.
4983          * For the whole directory, only dot/dotdot entry have no FID-in-dirent
4984          * and needs to get FID from LMA when readdir, it will not affect the
4985          * performance much. */
4986         if ((bh == NULL) || (le32_to_cpu(de->inode) != ent->oied_ino) ||
4987             (dot_dotdot != 0 && !osd_dot_dotdot_has_space(de, dot_dotdot))) {
4988                 *attr |= LUDA_IGNORE;
4989                 GOTO(out_journal, rc = 0);
4990         }
4991
4992         osd_id_gen(id, ent->oied_ino, OSD_OII_NOGEN);
4993         inode = osd_iget(info, dev, id);
4994         if (IS_ERR(inode)) {
4995                 rc = PTR_ERR(inode);
4996                 if (rc == -ENOENT || rc == -ESTALE) {
4997                         *attr |= LUDA_IGNORE;
4998                         rc = 0;
4999                 }
5000
5001                 GOTO(out_journal, rc);
5002         }
5003
5004         /* skip the REMOTE_PARENT_DIR. */
5005         if (inode == dev->od_mdt_map->omm_remote_parent->d_inode)
5006                 GOTO(out_inode, rc = 0);
5007
5008         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
5009         if (rc == 0) {
5010                 LASSERT(!(lma->lma_compat & LMAC_NOT_IN_OI));
5011
5012                 if (fid_is_sane(fid)) {
5013                         /* FID-in-dirent is valid. */
5014                         if (lu_fid_eq(fid, &lma->lma_self_fid))
5015                                 GOTO(out_inode, rc = 0);
5016
5017                         /* Do not repair under dryrun mode. */
5018                         if (*attr & LUDA_VERIFY_DRYRUN) {
5019                                 *attr |= LUDA_REPAIR;
5020                                 GOTO(out_inode, rc = 0);
5021                         }
5022
5023                         if (!dev->od_dirent_journal) {
5024                                 iput(inode);
5025                                 brelse(bh);
5026                                 if (hlock != NULL)
5027                                         ldiskfs_htree_unlock(hlock);
5028                                 else
5029                                         up_read(&obj->oo_ext_idx_sem);
5030                                 dev->od_dirent_journal = 1;
5031                                 goto again;
5032                         }
5033
5034                         *fid = lma->lma_self_fid;
5035                         dirty = true;
5036                         /* Update the FID-in-dirent. */
5037                         rc = osd_dirent_update(jh, sb, ent, fid, bh, de);
5038                         if (rc == 0)
5039                                 *attr |= LUDA_REPAIR;
5040                 } else {
5041                         /* Do not repair under dryrun mode. */
5042                         if (*attr & LUDA_VERIFY_DRYRUN) {
5043                                 *fid = lma->lma_self_fid;
5044                                 *attr |= LUDA_REPAIR;
5045                                 GOTO(out_inode, rc = 0);
5046                         }
5047
5048                         if (!dev->od_dirent_journal) {
5049                                 iput(inode);
5050                                 brelse(bh);
5051                                 if (hlock != NULL)
5052                                         ldiskfs_htree_unlock(hlock);
5053                                 else
5054                                         up_read(&obj->oo_ext_idx_sem);
5055                                 dev->od_dirent_journal = 1;
5056                                 goto again;
5057                         }
5058
5059                         *fid = lma->lma_self_fid;
5060                         dirty = true;
5061                         /* Append the FID-in-dirent. */
5062                         rc = osd_dirent_reinsert(env, jh, dir, inode, ent,
5063                                                  fid, bh, de, hlock);
5064                         if (rc == 0)
5065                                 *attr |= LUDA_REPAIR;
5066                 }
5067         } else if (rc == -ENODATA) {
5068                 /* Do not repair under dryrun mode. */
5069                 if (*attr & LUDA_VERIFY_DRYRUN) {
5070                         if (fid_is_sane(fid)) {
5071                                 *attr |= LUDA_REPAIR;
5072                         } else {
5073                                 lu_igif_build(fid, inode->i_ino,
5074                                               inode->i_generation);
5075                                 *attr |= LUDA_UPGRADE;
5076                         }
5077                         GOTO(out_inode, rc = 0);
5078                 }
5079
5080                 if (!dev->od_dirent_journal) {
5081                         iput(inode);
5082                         brelse(bh);
5083                         if (hlock != NULL)
5084                                 ldiskfs_htree_unlock(hlock);
5085                         else
5086                                 up_read(&obj->oo_ext_idx_sem);
5087                         dev->od_dirent_journal = 1;
5088                         goto again;
5089                 }
5090
5091                 dirty = true;
5092                 if (unlikely(fid_is_sane(fid))) {
5093                         /* FID-in-dirent exists, but FID-in-LMA is lost.
5094                          * Trust the FID-in-dirent, and add FID-in-LMA. */
5095                         rc = osd_ea_fid_set(info, inode, fid, 0, 0);
5096                         if (rc == 0)
5097                                 *attr |= LUDA_REPAIR;
5098                 } else {
5099                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
5100                         /* It is probably IGIF object. Only aappend the
5101                          * FID-in-dirent. OI scrub will process FID-in-LMA. */
5102                         rc = osd_dirent_reinsert(env, jh, dir, inode, ent,
5103                                                  fid, bh, de, hlock);
5104                         if (rc == 0)
5105                                 *attr |= LUDA_UPGRADE;
5106                 }
5107         }
5108
5109         GOTO(out_inode, rc);
5110
5111 out_inode:
5112         iput(inode);
5113
5114 out_journal:
5115         brelse(bh);
5116         if (hlock != NULL) {
5117                 ldiskfs_htree_unlock(hlock);
5118         } else {
5119                 if (dev->od_dirent_journal)
5120                         up_write(&obj->oo_ext_idx_sem);
5121                 else
5122                         up_read(&obj->oo_ext_idx_sem);
5123         }
5124         if (jh != NULL)
5125                 ldiskfs_journal_stop(jh);
5126         if (rc >= 0 && !dirty)
5127                 dev->od_dirent_journal = 0;
5128         return rc;
5129 }
5130
5131 /**
5132  * Returns the value at current position from iterator's in memory structure.
5133  *
5134  * \param di struct osd_it_ea, iterator's in memory structure
5135  * \param attr attr requested for dirent.
5136  * \param lde lustre dirent
5137  *
5138  * \retval   0 no error and \param lde has correct lustre dirent.
5139  * \retval -ve on error
5140  */
5141 static inline int osd_it_ea_rec(const struct lu_env *env,
5142                                 const struct dt_it *di,
5143                                 struct dt_rec *dtrec, __u32 attr)
5144 {
5145         struct osd_it_ea       *it    = (struct osd_it_ea *)di;
5146         struct osd_object      *obj   = it->oie_obj;
5147         struct osd_device      *dev   = osd_obj2dev(obj);
5148         struct osd_scrub       *scrub = &dev->od_scrub;
5149         struct scrub_file      *sf    = &scrub->os_file;
5150         struct osd_thread_info *oti   = osd_oti_get(env);
5151         struct osd_inode_id    *id    = &oti->oti_id;
5152         struct osd_idmap_cache *oic   = &oti->oti_cache;
5153         struct lu_fid          *fid   = &it->oie_dirent->oied_fid;
5154         struct lu_dirent       *lde   = (struct lu_dirent *)dtrec;
5155         __u32                   ino   = it->oie_dirent->oied_ino;
5156         int                     rc    = 0;
5157         ENTRY;
5158
5159         if (attr & LUDA_VERIFY) {
5160                 attr |= LUDA_TYPE;
5161                 if (unlikely(ino == osd_sb(dev)->s_root->d_inode->i_ino)) {
5162                         attr |= LUDA_IGNORE;
5163                         rc = 0;
5164                 } else {
5165                         rc = osd_dirent_check_repair(env, obj, it, fid, id,
5166                                                      &attr);
5167                 }
5168         } else {
5169                 attr &= ~LU_DIRENT_ATTRS_MASK;
5170                 if (!fid_is_sane(fid)) {
5171                         if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP))
5172                                 RETURN(-ENOENT);
5173
5174                         rc = osd_ea_fid_get(env, obj, ino, fid, id);
5175                 } else {
5176                         osd_id_gen(id, ino, OSD_OII_NOGEN);
5177                 }
5178         }
5179
5180         /* Pack the entry anyway, at least the offset is right. */
5181         osd_it_pack_dirent(lde, fid, it->oie_dirent->oied_off,
5182                            it->oie_dirent->oied_name,
5183                            it->oie_dirent->oied_namelen,
5184                            it->oie_dirent->oied_type, attr);
5185
5186         if (rc < 0)
5187                 RETURN(rc);
5188
5189         if (osd_remote_fid(env, dev, fid))
5190                 RETURN(0);
5191
5192         if (likely(!(attr & LUDA_IGNORE)))
5193                 rc = osd_add_oi_cache(oti, dev, id, fid);
5194
5195         if (!(attr & LUDA_VERIFY) &&
5196             (scrub->os_pos_current <= ino) &&
5197             ((sf->sf_flags & SF_INCONSISTENT) ||
5198              (sf->sf_flags & SF_UPGRADE && fid_is_igif(fid)) ||
5199              ldiskfs_test_bit(osd_oi_fid2idx(dev, fid), sf->sf_oi_bitmap)))
5200                 osd_consistency_check(oti, dev, oic);
5201
5202         RETURN(rc);
5203 }
5204
5205 /**
5206  * Returns a cookie for current position of the iterator head, so that
5207  * user can use this cookie to load/start the iterator next time.
5208  *
5209  * \param di iterator's in memory structure
5210  *
5211  * \retval cookie for current position, on success
5212  */
5213 static __u64 osd_it_ea_store(const struct lu_env *env, const struct dt_it *di)
5214 {
5215         struct osd_it_ea *it = (struct osd_it_ea *)di;
5216
5217         return it->oie_dirent->oied_off;
5218 }
5219
5220 /**
5221  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
5222  * to load a directory entry at a time and stored it i inn,
5223  * in iterator's in-memory data structure.
5224  *
5225  * \param di struct osd_it_ea, iterator's in memory structure
5226  *
5227  * \retval +ve on success
5228  * \retval -ve on error
5229  */
5230 static int osd_it_ea_load(const struct lu_env *env,
5231                           const struct dt_it *di, __u64 hash)
5232 {
5233         struct osd_it_ea *it = (struct osd_it_ea *)di;
5234         int rc;
5235
5236         ENTRY;
5237         it->oie_file.f_pos = hash;
5238
5239         rc =  osd_ldiskfs_it_fill(env, di);
5240         if (rc == 0)
5241                 rc = +1;
5242
5243         RETURN(rc);
5244 }
5245
5246 /**
5247  * Index lookup function for interoperability mode (b11826).
5248  *
5249  * \param key,  key i.e. file name to be searched
5250  *
5251  * \retval +ve, on success
5252  * \retval -ve, on error
5253  */
5254 static int osd_index_ea_lookup(const struct lu_env *env, struct dt_object *dt,
5255                                struct dt_rec *rec, const struct dt_key *key,
5256                                struct lustre_capa *capa)
5257 {
5258         struct osd_object *obj = osd_dt_obj(dt);
5259         int rc = 0;
5260
5261         ENTRY;
5262
5263         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
5264         LINVRNT(osd_invariant(obj));
5265
5266         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
5267                 return -EACCES;
5268
5269         rc = osd_ea_lookup_rec(env, obj, rec, key);
5270         if (rc == 0)
5271                 rc = +1;
5272         RETURN(rc);
5273 }
5274
5275 /**
5276  * Index and Iterator operations for interoperability
5277  * mode (i.e. to run 2.0 mds on 1.8 disk) (b11826)
5278  */
5279 static const struct dt_index_operations osd_index_ea_ops = {
5280         .dio_lookup         = osd_index_ea_lookup,
5281         .dio_declare_insert = osd_index_declare_ea_insert,
5282         .dio_insert         = osd_index_ea_insert,
5283         .dio_declare_delete = osd_index_declare_ea_delete,
5284         .dio_delete         = osd_index_ea_delete,
5285         .dio_it     = {
5286                 .init     = osd_it_ea_init,
5287                 .fini     = osd_it_ea_fini,
5288                 .get      = osd_it_ea_get,
5289                 .put      = osd_it_ea_put,
5290                 .next     = osd_it_ea_next,
5291                 .key      = osd_it_ea_key,
5292                 .key_size = osd_it_ea_key_size,
5293                 .rec      = osd_it_ea_rec,
5294                 .store    = osd_it_ea_store,
5295                 .load     = osd_it_ea_load
5296         }
5297 };
5298
5299 static void *osd_key_init(const struct lu_context *ctx,
5300                           struct lu_context_key *key)
5301 {
5302         struct osd_thread_info *info;
5303
5304         OBD_ALLOC_PTR(info);
5305         if (info == NULL)
5306                 return ERR_PTR(-ENOMEM);
5307
5308         OBD_ALLOC(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5309         if (info->oti_it_ea_buf == NULL)
5310                 goto out_free_info;
5311
5312         info->oti_env = container_of(ctx, struct lu_env, le_ctx);
5313
5314         info->oti_hlock = ldiskfs_htree_lock_alloc();
5315         if (info->oti_hlock == NULL)
5316                 goto out_free_ea;
5317
5318         return info;
5319
5320  out_free_ea:
5321         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5322  out_free_info:
5323         OBD_FREE_PTR(info);
5324         return ERR_PTR(-ENOMEM);
5325 }
5326
5327 static void osd_key_fini(const struct lu_context *ctx,
5328                          struct lu_context_key *key, void* data)
5329 {
5330         struct osd_thread_info *info = data;
5331
5332         if (info->oti_hlock != NULL)
5333                 ldiskfs_htree_lock_free(info->oti_hlock);
5334         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5335         lu_buf_free(&info->oti_iobuf.dr_pg_buf);
5336         lu_buf_free(&info->oti_iobuf.dr_bl_buf);
5337         OBD_FREE_PTR(info);
5338 }
5339
5340 static void osd_key_exit(const struct lu_context *ctx,
5341                          struct lu_context_key *key, void *data)
5342 {
5343         struct osd_thread_info *info = data;
5344
5345         LASSERT(info->oti_r_locks == 0);
5346         LASSERT(info->oti_w_locks == 0);
5347         LASSERT(info->oti_txns    == 0);
5348 }
5349
5350 /* type constructor/destructor: osd_type_init, osd_type_fini */
5351 LU_TYPE_INIT_FINI(osd, &osd_key);
5352
5353 struct lu_context_key osd_key = {
5354         .lct_tags = LCT_DT_THREAD | LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL,
5355         .lct_init = osd_key_init,
5356         .lct_fini = osd_key_fini,
5357         .lct_exit = osd_key_exit
5358 };
5359
5360
5361 static int osd_device_init(const struct lu_env *env, struct lu_device *d,
5362                            const char *name, struct lu_device *next)
5363 {
5364         struct osd_device *osd = osd_dev(d);
5365
5366         if (strlcpy(osd->od_svname, name, sizeof(osd->od_svname))
5367             >= sizeof(osd->od_svname))
5368                 return -E2BIG;
5369         return osd_procfs_init(osd, name);
5370 }
5371
5372 static int osd_shutdown(const struct lu_env *env, struct osd_device *o)
5373 {
5374         ENTRY;
5375
5376         /* shutdown quota slave instance associated with the device */
5377         if (o->od_quota_slave != NULL) {
5378                 qsd_fini(env, o->od_quota_slave);
5379                 o->od_quota_slave = NULL;
5380         }
5381
5382         RETURN(0);
5383 }
5384
5385 static void osd_umount(const struct lu_env *env, struct osd_device *o)
5386 {
5387         ENTRY;
5388
5389         if (o->od_fsops) {
5390                 fsfilt_put_ops(o->od_fsops);
5391                 o->od_fsops = NULL;
5392         }
5393
5394         if (o->od_mnt != NULL) {
5395                 shrink_dcache_sb(osd_sb(o));
5396                 osd_sync(env, &o->od_dt_dev);
5397
5398                 mntput(o->od_mnt);
5399                 o->od_mnt = NULL;
5400         }
5401
5402         EXIT;
5403 }
5404
5405 static int osd_mount(const struct lu_env *env,
5406                      struct osd_device *o, struct lustre_cfg *cfg)
5407 {
5408         const char              *name  = lustre_cfg_string(cfg, 0);
5409         const char              *dev  = lustre_cfg_string(cfg, 1);
5410         const char              *opts;
5411         unsigned long            page, s_flags, lmd_flags = 0;
5412         struct page             *__page;
5413         struct file_system_type *type;
5414         char                    *options = NULL;
5415         char                    *str;
5416         struct osd_thread_info  *info = osd_oti_get(env);
5417         struct lu_fid           *fid = &info->oti_fid;
5418         struct inode            *inode;
5419         int                      rc = 0;
5420         ENTRY;
5421
5422         if (o->od_mnt != NULL)
5423                 RETURN(0);
5424
5425         if (strlen(dev) >= sizeof(o->od_mntdev))
5426                 RETURN(-E2BIG);
5427         strcpy(o->od_mntdev, dev);
5428
5429         o->od_fsops = fsfilt_get_ops(mt_str(LDD_MT_LDISKFS));
5430         if (IS_ERR(o->od_fsops)) {
5431                 CERROR("%s: Can't find fsfilt_ldiskfs\n", name);
5432                 o->od_fsops = NULL;
5433                 RETURN(-ENOTSUPP);
5434         }
5435
5436         OBD_PAGE_ALLOC(__page, GFP_IOFS);
5437         if (__page == NULL)
5438                 GOTO(out, rc = -ENOMEM);
5439
5440         str = lustre_cfg_string(cfg, 2);
5441         s_flags = simple_strtoul(str, NULL, 0);
5442         str = strstr(str, ":");
5443         if (str)
5444                 lmd_flags = simple_strtoul(str + 1, NULL, 0);
5445         opts = lustre_cfg_string(cfg, 3);
5446         page = (unsigned long)page_address(__page);
5447         options = (char *)page;
5448         *options = '\0';
5449         if (opts == NULL)
5450                 strcat(options, "user_xattr,acl");
5451         else
5452                 strcat(options, opts);
5453
5454         /* Glom up mount options */
5455         if (*options != '\0')
5456                 strcat(options, ",");
5457         strlcat(options, "no_mbcache", PAGE_CACHE_SIZE);
5458
5459         type = get_fs_type("ldiskfs");
5460         if (!type) {
5461                 CERROR("%s: cannot find ldiskfs module\n", name);
5462                 GOTO(out, rc = -ENODEV);
5463         }
5464
5465         o->od_mnt = vfs_kern_mount(type, s_flags, dev, options);
5466         module_put(type->owner);
5467
5468         if (IS_ERR(o->od_mnt)) {
5469                 rc = PTR_ERR(o->od_mnt);
5470                 o->od_mnt = NULL;
5471                 CERROR("%s: can't mount %s: %d\n", name, dev, rc);
5472                 GOTO(out, rc);
5473         }
5474
5475 #ifdef HAVE_DEV_SET_RDONLY
5476         if (dev_check_rdonly(o->od_mnt->mnt_sb->s_bdev)) {
5477                 CERROR("%s: underlying device %s is marked as read-only. "
5478                        "Setup failed\n", name, dev);
5479                 GOTO(out_mnt, rc = -EROFS);
5480         }
5481 #endif
5482
5483         if (!LDISKFS_HAS_COMPAT_FEATURE(o->od_mnt->mnt_sb,
5484             LDISKFS_FEATURE_COMPAT_HAS_JOURNAL)) {
5485                 CERROR("%s: device %s is mounted w/o journal\n", name, dev);
5486                 GOTO(out_mnt, rc = -EINVAL);
5487         }
5488
5489         inode = osd_sb(o)->s_root->d_inode;
5490         ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NO_OI);
5491         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
5492         rc = osd_ea_fid_set(info, inode, fid, LMAC_NOT_IN_OI, 0);
5493         if (rc != 0) {
5494                 CERROR("%s: failed to set lma on %s root inode\n", name, dev);
5495                 GOTO(out_mnt, rc);
5496         }
5497
5498         if (lmd_flags & LMD_FLG_NOSCRUB)
5499                 o->od_noscrub = 1;
5500
5501         GOTO(out, rc = 0);
5502
5503 out_mnt:
5504         mntput(o->od_mnt);
5505         o->od_mnt = NULL;
5506
5507 out:
5508         if (__page)
5509                 OBD_PAGE_FREE(__page);
5510         if (rc)
5511                 fsfilt_put_ops(o->od_fsops);
5512
5513         return rc;
5514 }
5515
5516 static struct lu_device *osd_device_fini(const struct lu_env *env,
5517                                          struct lu_device *d)
5518 {
5519         struct osd_device *o = osd_dev(d);
5520         ENTRY;
5521
5522         osd_procfs_fini(o);
5523         osd_shutdown(env, o);
5524         osd_scrub_cleanup(env, o);
5525         osd_obj_map_fini(o);
5526         osd_umount(env, o);
5527
5528         RETURN(NULL);
5529 }
5530
5531 static int osd_device_init0(const struct lu_env *env,
5532                             struct osd_device *o,
5533                             struct lustre_cfg *cfg)
5534 {
5535         struct lu_device        *l = osd2lu_dev(o);
5536         struct osd_thread_info *info;
5537         int                     rc;
5538         int                     cplen = 0;
5539
5540         /* if the module was re-loaded, env can loose its keys */
5541         rc = lu_env_refill((struct lu_env *) env);
5542         if (rc)
5543                 GOTO(out, rc);
5544         info = osd_oti_get(env);
5545         LASSERT(info);
5546
5547         l->ld_ops = &osd_lu_ops;
5548         o->od_dt_dev.dd_ops = &osd_dt_ops;
5549
5550         spin_lock_init(&o->od_osfs_lock);
5551         mutex_init(&o->od_otable_mutex);
5552         o->od_osfs_age = cfs_time_shift_64(-1000);
5553
5554         o->od_capa_hash = init_capa_hash();
5555         if (o->od_capa_hash == NULL)
5556                 GOTO(out, rc = -ENOMEM);
5557
5558         o->od_read_cache = 1;
5559         o->od_writethrough_cache = 1;
5560         o->od_readcache_max_filesize = OSD_MAX_CACHE_SIZE;
5561
5562         rc = osd_mount(env, o, cfg);
5563         if (rc)
5564                 GOTO(out_capa, rc);
5565
5566         cplen = strlcpy(o->od_svname, lustre_cfg_string(cfg, 4),
5567                         sizeof(o->od_svname));
5568         if (cplen >= sizeof(o->od_svname)) {
5569                 rc = -E2BIG;
5570                 GOTO(out_mnt, rc);
5571         }
5572
5573         if (server_name_is_ost(o->od_svname))
5574                 o->od_is_ost = 1;
5575
5576         rc = osd_obj_map_init(env, o);
5577         if (rc != 0)
5578                 GOTO(out_mnt, rc);
5579
5580         rc = lu_site_init(&o->od_site, l);
5581         if (rc != 0)
5582                 GOTO(out_compat, rc);
5583         o->od_site.ls_bottom_dev = l;
5584
5585         rc = lu_site_init_finish(&o->od_site);
5586         if (rc != 0)
5587                 GOTO(out_site, rc);
5588
5589         CFS_INIT_LIST_HEAD(&o->od_ios_list);
5590         /* setup scrub, including OI files initialization */
5591         rc = osd_scrub_setup(env, o);
5592         if (rc < 0)
5593                 GOTO(out_site, rc);
5594
5595         rc = osd_procfs_init(o, o->od_svname);
5596         if (rc != 0) {
5597                 CERROR("%s: can't initialize procfs: rc = %d\n",
5598                        o->od_svname, rc);
5599                 GOTO(out_scrub, rc);
5600         }
5601
5602         LASSERT(l->ld_site->ls_linkage.next && l->ld_site->ls_linkage.prev);
5603
5604         /* initialize quota slave instance */
5605         o->od_quota_slave = qsd_init(env, o->od_svname, &o->od_dt_dev,
5606                                      o->od_proc_entry);
5607         if (IS_ERR(o->od_quota_slave)) {
5608                 rc = PTR_ERR(o->od_quota_slave);
5609                 o->od_quota_slave = NULL;
5610                 GOTO(out_procfs, rc);
5611         }
5612
5613         RETURN(0);
5614
5615 out_procfs:
5616         osd_procfs_fini(o);
5617 out_scrub:
5618         osd_scrub_cleanup(env, o);
5619 out_site:
5620         lu_site_fini(&o->od_site);
5621 out_compat:
5622         osd_obj_map_fini(o);
5623 out_mnt:
5624         osd_umount(env, o);
5625 out_capa:
5626         cleanup_capa_hash(o->od_capa_hash);
5627 out:
5628         return rc;
5629 }
5630
5631 static struct lu_device *osd_device_alloc(const struct lu_env *env,
5632                                           struct lu_device_type *t,
5633                                           struct lustre_cfg *cfg)
5634 {
5635         struct osd_device *o;
5636         int                rc;
5637
5638         OBD_ALLOC_PTR(o);
5639         if (o == NULL)
5640                 return ERR_PTR(-ENOMEM);
5641
5642         rc = dt_device_init(&o->od_dt_dev, t);
5643         if (rc == 0) {
5644                 /* Because the ctx might be revived in dt_device_init,
5645                  * refill the env here */
5646                 lu_env_refill((struct lu_env *)env);
5647                 rc = osd_device_init0(env, o, cfg);
5648                 if (rc)
5649                         dt_device_fini(&o->od_dt_dev);
5650         }
5651
5652         if (unlikely(rc != 0))
5653                 OBD_FREE_PTR(o);
5654
5655         return rc == 0 ? osd2lu_dev(o) : ERR_PTR(rc);
5656 }
5657
5658 static struct lu_device *osd_device_free(const struct lu_env *env,
5659                                          struct lu_device *d)
5660 {
5661         struct osd_device *o = osd_dev(d);
5662         ENTRY;
5663
5664         cleanup_capa_hash(o->od_capa_hash);
5665         /* XXX: make osd top device in order to release reference */
5666         d->ld_site->ls_top_dev = d;
5667         lu_site_purge(env, d->ld_site, -1);
5668         if (!cfs_hash_is_empty(d->ld_site->ls_obj_hash)) {
5669                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, D_ERROR, NULL);
5670                 lu_site_print(env, d->ld_site, &msgdata, lu_cdebug_printer);
5671         }
5672         lu_site_fini(&o->od_site);
5673         dt_device_fini(&o->od_dt_dev);
5674         OBD_FREE_PTR(o);
5675         RETURN(NULL);
5676 }
5677
5678 static int osd_process_config(const struct lu_env *env,
5679                               struct lu_device *d, struct lustre_cfg *cfg)
5680 {
5681         struct osd_device *o = osd_dev(d);
5682         int err;
5683         ENTRY;
5684
5685         switch(cfg->lcfg_command) {
5686         case LCFG_SETUP:
5687                 err = osd_mount(env, o, cfg);
5688                 break;
5689         case LCFG_CLEANUP:
5690                 lu_dev_del_linkage(d->ld_site, d);
5691                 err = osd_shutdown(env, o);
5692                 break;
5693         default:
5694                 err = -ENOSYS;
5695         }
5696
5697         RETURN(err);
5698 }
5699
5700 static int osd_recovery_complete(const struct lu_env *env,
5701                                  struct lu_device *d)
5702 {
5703         struct osd_device       *osd = osd_dev(d);
5704         int                      rc = 0;
5705         ENTRY;
5706
5707         if (osd->od_quota_slave == NULL)
5708                 RETURN(0);
5709
5710         /* start qsd instance on recovery completion, this notifies the quota
5711          * slave code that we are about to process new requests now */
5712         rc = qsd_start(env, osd->od_quota_slave);
5713         RETURN(rc);
5714 }
5715
5716 /*
5717  * we use exports to track all osd users
5718  */
5719 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
5720                            struct obd_device *obd, struct obd_uuid *cluuid,
5721                            struct obd_connect_data *data, void *localdata)
5722 {
5723         struct osd_device    *osd = osd_dev(obd->obd_lu_dev);
5724         struct lustre_handle  conn;
5725         int                   rc;
5726         ENTRY;
5727
5728         CDEBUG(D_CONFIG, "connect #%d\n", osd->od_connects);
5729
5730         rc = class_connect(&conn, obd, cluuid);
5731         if (rc)
5732                 RETURN(rc);
5733
5734         *exp = class_conn2export(&conn);
5735
5736         spin_lock(&osd->od_osfs_lock);
5737         osd->od_connects++;
5738         spin_unlock(&osd->od_osfs_lock);
5739
5740         RETURN(0);
5741 }
5742
5743 /*
5744  * once last export (we don't count self-export) disappeared
5745  * osd can be released
5746  */
5747 static int osd_obd_disconnect(struct obd_export *exp)
5748 {
5749         struct obd_device *obd = exp->exp_obd;
5750         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
5751         int                rc, release = 0;
5752         ENTRY;
5753
5754         /* Only disconnect the underlying layers on the final disconnect. */
5755         spin_lock(&osd->od_osfs_lock);
5756         osd->od_connects--;
5757         if (osd->od_connects == 0)
5758                 release = 1;
5759         spin_unlock(&osd->od_osfs_lock);
5760
5761         rc = class_disconnect(exp); /* bz 9811 */
5762
5763         if (rc == 0 && release)
5764                 class_manual_cleanup(obd);
5765         RETURN(rc);
5766 }
5767
5768 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
5769                        struct lu_device *dev)
5770 {
5771         struct osd_device *osd = osd_dev(dev);
5772         int                result = 0;
5773         ENTRY;
5774
5775         if (osd->od_quota_slave != NULL)
5776                 /* set up quota slave objects */
5777                 result = qsd_prepare(env, osd->od_quota_slave);
5778
5779         RETURN(result);
5780 }
5781
5782 static const struct lu_object_operations osd_lu_obj_ops = {
5783         .loo_object_init      = osd_object_init,
5784         .loo_object_delete    = osd_object_delete,
5785         .loo_object_release   = osd_object_release,
5786         .loo_object_free      = osd_object_free,
5787         .loo_object_print     = osd_object_print,
5788         .loo_object_invariant = osd_object_invariant
5789 };
5790
5791 const struct lu_device_operations osd_lu_ops = {
5792         .ldo_object_alloc      = osd_object_alloc,
5793         .ldo_process_config    = osd_process_config,
5794         .ldo_recovery_complete = osd_recovery_complete,
5795         .ldo_prepare           = osd_prepare,
5796 };
5797
5798 static const struct lu_device_type_operations osd_device_type_ops = {
5799         .ldto_init = osd_type_init,
5800         .ldto_fini = osd_type_fini,
5801
5802         .ldto_start = osd_type_start,
5803         .ldto_stop  = osd_type_stop,
5804
5805         .ldto_device_alloc = osd_device_alloc,
5806         .ldto_device_free  = osd_device_free,
5807
5808         .ldto_device_init    = osd_device_init,
5809         .ldto_device_fini    = osd_device_fini
5810 };
5811
5812 struct lu_device_type osd_device_type = {
5813         .ldt_tags     = LU_DEVICE_DT,
5814         .ldt_name     = LUSTRE_OSD_LDISKFS_NAME,
5815         .ldt_ops      = &osd_device_type_ops,
5816         .ldt_ctx_tags = LCT_LOCAL,
5817 };
5818
5819 /*
5820  * lprocfs legacy support.
5821  */
5822 static struct obd_ops osd_obd_device_ops = {
5823         .o_owner = THIS_MODULE,
5824         .o_connect      = osd_obd_connect,
5825         .o_disconnect   = osd_obd_disconnect
5826 };
5827
5828 static int __init osd_mod_init(void)
5829 {
5830         struct lprocfs_static_vars lvars;
5831
5832         osd_oi_mod_init();
5833         lprocfs_osd_init_vars(&lvars);
5834         return class_register_type(&osd_obd_device_ops, NULL, lvars.module_vars,
5835                                    LUSTRE_OSD_LDISKFS_NAME, &osd_device_type);
5836 }
5837
5838 static void __exit osd_mod_exit(void)
5839 {
5840         class_unregister_type(LUSTRE_OSD_LDISKFS_NAME);
5841 }
5842
5843 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
5844 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_LDISKFS_NAME")");
5845 MODULE_LICENSE("GPL");
5846
5847 cfs_module(osd, "0.1.0", osd_mod_init, osd_mod_exit);