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