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