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