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