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