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