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