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