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