Whamcloud - gitweb
475fbca60b0d0c2c6c5e77f8c16b7b6b930bf8c1
[fs/lustre-release.git] / lustre / osd-ldiskfs / osd_scrub.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,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2012, 2013, Intel Corporation.
24  */
25 /*
26  * lustre/osd-ldiskfs/osd_scrub.c
27  *
28  * Top-level entry points into osd module
29  *
30  * The OI scrub is used for rebuilding Object Index files when restores MDT from
31  * file-level backup.
32  *
33  * The otable based iterator scans ldiskfs inode table to feed up layer LFSCK.
34  *
35  * Author: Fan Yong <yong.fan@whamcloud.com>
36  */
37
38 #ifndef EXPORT_SYMTAB
39 # define EXPORT_SYMTAB
40 #endif
41 #define DEBUG_SUBSYSTEM S_MDS
42
43 #include <lustre/lustre_idl.h>
44 #include <lustre_disk.h>
45 #include <dt_object.h>
46
47 #include "osd_internal.h"
48 #include "osd_oi.h"
49 #include "osd_scrub.h"
50
51 #define HALF_SEC        (CFS_HZ >> 1)
52
53 #define OSD_OTABLE_MAX_HASH             0x00000000ffffffffULL
54
55 #define SCRUB_NEXT_BREAK        1 /* exit current loop and process next group */
56 #define SCRUB_NEXT_CONTINUE     2 /* skip current object and process next bit */
57 #define SCRUB_NEXT_EXIT         3 /* exit all the loops */
58 #define SCRUB_NEXT_WAIT         4 /* wait for free cache slot */
59 #define SCRUB_NEXT_CRASH        5 /* simulate system crash during OI scrub */
60 #define SCRUB_NEXT_FATAL        6 /* simulate failure during OI scrub */
61 #define SCRUB_NEXT_NOSCRUB      7 /* new created object, no scrub on it */
62 #define SCRUB_NEXT_NOLMA        8 /* the inode has no FID-in-LMA */
63
64 /* misc functions */
65
66 static inline struct osd_device *osd_scrub2dev(struct osd_scrub *scrub)
67 {
68         return container_of0(scrub, struct osd_device, od_scrub);
69 }
70
71 static inline struct super_block *osd_scrub2sb(struct osd_scrub *scrub)
72 {
73         return osd_sb(osd_scrub2dev(scrub));
74 }
75
76 static inline int osd_scrub_has_window(struct osd_scrub *scrub,
77                                        struct osd_otable_cache *ooc)
78 {
79         return scrub->os_pos_current < ooc->ooc_pos_preload + SCRUB_WINDOW_SIZE;
80 }
81
82 /**
83  * update/insert/delete the specified OI mapping (@fid @id) according to the ops
84  *
85  * \retval   1, changed nothing
86  * \retval   0, changed successfully
87  * \retval -ve, on error
88  */
89 static int osd_scrub_refresh_mapping(struct osd_thread_info *info,
90                                      struct osd_device *dev,
91                                      const struct lu_fid *fid,
92                                      const struct osd_inode_id *id, int ops)
93 {
94         struct lu_fid         *oi_fid = &info->oti_fid2;
95         struct osd_inode_id   *oi_id  = &info->oti_id2;
96         struct iam_container  *bag;
97         struct iam_path_descr *ipd;
98         handle_t              *jh;
99         int                    rc;
100         ENTRY;
101
102         fid_cpu_to_be(oi_fid, fid);
103         osd_id_pack(oi_id, id);
104         jh = ldiskfs_journal_start_sb(osd_sb(dev),
105                                       osd_dto_credits_noquota[ops]);
106         if (IS_ERR(jh)) {
107                 rc = PTR_ERR(jh);
108                 CERROR("%.16s: fail to start trans for scrub store: rc = %d\n",
109                        LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name, rc);
110                 RETURN(rc);
111         }
112
113         bag = &osd_fid2oi(dev, fid)->oi_dir.od_container;
114         ipd = osd_idx_ipd_get(info->oti_env, bag);
115         if (unlikely(ipd == NULL)) {
116                 ldiskfs_journal_stop(jh);
117                 CERROR("%.16s: fail to get ipd for scrub store\n",
118                        LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name);
119                 RETURN(-ENOMEM);
120         }
121
122         switch (ops) {
123         case DTO_INDEX_UPDATE:
124                 rc = iam_update(jh, bag, (const struct iam_key *)oi_fid,
125                                 (struct iam_rec *)oi_id, ipd);
126                 if (unlikely(rc == -ENOENT)) {
127                         /* Some unlink thread may removed the OI mapping. */
128                         rc = 1;
129                 }
130                 break;
131         case DTO_INDEX_INSERT:
132                 rc = iam_insert(jh, bag, (const struct iam_key *)oi_fid,
133                                 (struct iam_rec *)oi_id, ipd);
134                 if (unlikely(rc == -EEXIST)) {
135                         rc = 1;
136                         /* XXX: There are trouble things when adding OI
137                          *      mapping for IGIF object, which may cause
138                          *      multiple objects to be mapped to the same
139                          *      IGIF formatted FID. Consider the following
140                          *      situations:
141                          *
142                          *      1) The MDT is upgrading from 1.8 device.
143                          *      The OI scrub generates IGIF FID1 for the
144                          *      OBJ1 and adds the OI mapping.
145                          *
146                          *      2) For some reason, the OI scrub does not
147                          *      process all the IGIF objects completely.
148                          *
149                          *      3) The MDT is backuped and restored against
150                          *      this device.
151                          *
152                          *      4) When the MDT mounts up, the OI scrub will
153                          *      try to rebuild the OI files. For some IGIF
154                          *      object, OBJ2, which was not processed by the
155                          *      OI scrub before the backup/restore, and the
156                          *      new generated IGIF formatted FID may be just
157                          *      the FID1, the same as OBJ1.
158                          *
159                          *      Under such case, the OI scrub cannot know how
160                          *      to generate new FID for the OBJ2.
161                          *
162                          *      Currently, we do nothing for that. One possible
163                          *      solution is to generate new normal FID for the
164                          *      conflict object.
165                          *
166                          *      Anyway, it is rare, only exists in theory. */
167                 }
168                 break;
169         case DTO_INDEX_DELETE:
170                 rc = iam_delete(jh, bag, (const struct iam_key *)oi_fid, ipd);
171                 if (rc == -ENOENT) {
172                         /* It is normal that the unlink thread has removed the
173                          * OI mapping already. */
174                         rc = 1;
175                 }
176                 break;
177         default:
178                 LASSERTF(0, "Unexpected ops %d\n", ops);
179                 break;
180         }
181         osd_ipd_put(info->oti_env, bag, ipd);
182         ldiskfs_journal_stop(jh);
183         RETURN(rc);
184 }
185
186 /* OI_scrub file ops */
187
188 static void osd_scrub_file_to_cpu(struct scrub_file *des,
189                                   struct scrub_file *src)
190 {
191         memcpy(des->sf_uuid, src->sf_uuid, 16);
192         des->sf_flags   = le64_to_cpu(src->sf_flags);
193         des->sf_magic   = le32_to_cpu(src->sf_magic);
194         des->sf_status  = le16_to_cpu(src->sf_status);
195         des->sf_param   = le16_to_cpu(src->sf_param);
196         des->sf_time_last_complete      =
197                                 le64_to_cpu(src->sf_time_last_complete);
198         des->sf_time_latest_start       =
199                                 le64_to_cpu(src->sf_time_latest_start);
200         des->sf_time_last_checkpoint    =
201                                 le64_to_cpu(src->sf_time_last_checkpoint);
202         des->sf_pos_latest_start        =
203                                 le64_to_cpu(src->sf_pos_latest_start);
204         des->sf_pos_last_checkpoint     =
205                                 le64_to_cpu(src->sf_pos_last_checkpoint);
206         des->sf_pos_first_inconsistent  =
207                                 le64_to_cpu(src->sf_pos_first_inconsistent);
208         des->sf_items_checked           =
209                                 le64_to_cpu(src->sf_items_checked);
210         des->sf_items_updated           =
211                                 le64_to_cpu(src->sf_items_updated);
212         des->sf_items_failed            =
213                                 le64_to_cpu(src->sf_items_failed);
214         des->sf_items_updated_prior     =
215                                 le64_to_cpu(src->sf_items_updated_prior);
216         des->sf_run_time        = le32_to_cpu(src->sf_run_time);
217         des->sf_success_count   = le32_to_cpu(src->sf_success_count);
218         des->sf_oi_count        = le16_to_cpu(src->sf_oi_count);
219         memcpy(des->sf_oi_bitmap, src->sf_oi_bitmap, SCRUB_OI_BITMAP_SIZE);
220 }
221
222 static void osd_scrub_file_to_le(struct scrub_file *des,
223                                  struct scrub_file *src)
224 {
225         memcpy(des->sf_uuid, src->sf_uuid, 16);
226         des->sf_flags   = cpu_to_le64(src->sf_flags);
227         des->sf_magic   = cpu_to_le32(src->sf_magic);
228         des->sf_status  = cpu_to_le16(src->sf_status);
229         des->sf_param   = cpu_to_le16(src->sf_param);
230         des->sf_time_last_complete      =
231                                 cpu_to_le64(src->sf_time_last_complete);
232         des->sf_time_latest_start       =
233                                 cpu_to_le64(src->sf_time_latest_start);
234         des->sf_time_last_checkpoint    =
235                                 cpu_to_le64(src->sf_time_last_checkpoint);
236         des->sf_pos_latest_start        =
237                                 cpu_to_le64(src->sf_pos_latest_start);
238         des->sf_pos_last_checkpoint     =
239                                 cpu_to_le64(src->sf_pos_last_checkpoint);
240         des->sf_pos_first_inconsistent  =
241                                 cpu_to_le64(src->sf_pos_first_inconsistent);
242         des->sf_items_checked           =
243                                 cpu_to_le64(src->sf_items_checked);
244         des->sf_items_updated           =
245                                 cpu_to_le64(src->sf_items_updated);
246         des->sf_items_failed            =
247                                 cpu_to_le64(src->sf_items_failed);
248         des->sf_items_updated_prior     =
249                                 cpu_to_le64(src->sf_items_updated_prior);
250         des->sf_run_time        = cpu_to_le32(src->sf_run_time);
251         des->sf_success_count   = cpu_to_le32(src->sf_success_count);
252         des->sf_oi_count        = cpu_to_le16(src->sf_oi_count);
253         memcpy(des->sf_oi_bitmap, src->sf_oi_bitmap, SCRUB_OI_BITMAP_SIZE);
254 }
255
256 static void osd_scrub_file_init(struct osd_scrub *scrub, __u8 *uuid)
257 {
258         struct scrub_file *sf = &scrub->os_file;
259
260         memset(sf, 0, sizeof(*sf));
261         memcpy(sf->sf_uuid, uuid, 16);
262         sf->sf_magic = SCRUB_MAGIC_V1;
263         sf->sf_status = SS_INIT;
264 }
265
266 void osd_scrub_file_reset(struct osd_scrub *scrub, __u8 *uuid, __u64 flags)
267 {
268         struct scrub_file *sf = &scrub->os_file;
269
270         CDEBUG(D_LFSCK, "Reset OI scrub file, flags = "LPX64"\n", flags);
271         memcpy(sf->sf_uuid, uuid, 16);
272         sf->sf_status = SS_INIT;
273         sf->sf_flags |= flags;
274         sf->sf_param = 0;
275         sf->sf_run_time = 0;
276         sf->sf_time_latest_start = 0;
277         sf->sf_time_last_checkpoint = 0;
278         sf->sf_pos_latest_start = 0;
279         sf->sf_pos_last_checkpoint = 0;
280         sf->sf_pos_first_inconsistent = 0;
281         sf->sf_items_checked = 0;
282         sf->sf_items_updated = 0;
283         sf->sf_items_failed = 0;
284         sf->sf_items_updated_prior = 0;
285         sf->sf_items_noscrub = 0;
286         sf->sf_items_igif = 0;
287 }
288
289 static int osd_scrub_file_load(struct osd_scrub *scrub)
290 {
291         loff_t  pos  = 0;
292         char   *name = LDISKFS_SB(osd_scrub2sb(scrub))->s_es->s_volume_name;
293         int     len  = sizeof(scrub->os_file_disk);
294         int     rc;
295
296         rc = osd_ldiskfs_read(scrub->os_inode, &scrub->os_file_disk, len, &pos);
297         if (rc == len) {
298                 struct scrub_file *sf = &scrub->os_file;
299
300                 osd_scrub_file_to_cpu(sf, &scrub->os_file_disk);
301                 if (sf->sf_magic != SCRUB_MAGIC_V1) {
302                         CWARN("%.16s: invalid scrub magic 0x%x != 0x%x\n,",
303                               name, sf->sf_magic, SCRUB_MAGIC_V1);
304                         /* Process it as new scrub file. */
305                         rc = -ENOENT;
306                 } else {
307                         rc = 0;
308                 }
309         } else if (rc != 0) {
310                 CERROR("%.16s: fail to load scrub file, expected = %d, "
311                        "rc = %d\n", name, len, rc);
312                 if (rc > 0)
313                         rc = -EFAULT;
314         } else {
315                 /* return -ENOENT for empty scrub file case. */
316                 rc = -ENOENT;
317         }
318
319         return rc;
320 }
321
322 int osd_scrub_file_store(struct osd_scrub *scrub)
323 {
324         struct osd_device *dev;
325         handle_t          *jh;
326         loff_t             pos     = 0;
327         int                len     = sizeof(scrub->os_file_disk);
328         int                credits;
329         int                rc;
330
331         dev = container_of0(scrub, struct osd_device, od_scrub);
332         credits = osd_dto_credits_noquota[DTO_WRITE_BASE] +
333                   osd_dto_credits_noquota[DTO_WRITE_BLOCK];
334         jh = ldiskfs_journal_start_sb(osd_sb(dev), credits);
335         if (IS_ERR(jh)) {
336                 rc = PTR_ERR(jh);
337                 CERROR("%.16s: fail to start trans for scrub store, rc = %d\n",
338                        LDISKFS_SB(osd_scrub2sb(scrub))->s_es->s_volume_name,rc);
339                 return rc;
340         }
341
342         osd_scrub_file_to_le(&scrub->os_file_disk, &scrub->os_file);
343         rc = osd_ldiskfs_write_record(scrub->os_inode, &scrub->os_file_disk,
344                                       len, 0, &pos, jh);
345         ldiskfs_journal_stop(jh);
346         if (rc != 0)
347                 CERROR("%.16s: fail to store scrub file, expected = %d, "
348                        "rc = %d\n",
349                        LDISKFS_SB(osd_scrub2sb(scrub))->s_es->s_volume_name,
350                        len, rc);
351         scrub->os_time_last_checkpoint = cfs_time_current();
352         scrub->os_time_next_checkpoint = scrub->os_time_last_checkpoint +
353                                 cfs_time_seconds(SCRUB_CHECKPOINT_INTERVAL);
354         return rc;
355 }
356
357 /* OI scrub APIs */
358
359 static int osd_scrub_prep(struct osd_device *dev)
360 {
361         struct osd_scrub     *scrub  = &dev->od_scrub;
362         struct ptlrpc_thread *thread = &scrub->os_thread;
363         struct scrub_file    *sf     = &scrub->os_file;
364         __u32                 flags  = scrub->os_start_flags;
365         int                   rc;
366         ENTRY;
367
368         down_write(&scrub->os_rwsem);
369         if (flags & SS_SET_FAILOUT)
370                 sf->sf_param |= SP_FAILOUT;
371
372         if (flags & SS_CLEAR_FAILOUT)
373                 sf->sf_param &= ~SP_FAILOUT;
374
375         if (flags & SS_RESET)
376                 osd_scrub_file_reset(scrub,
377                         LDISKFS_SB(osd_sb(dev))->s_es->s_uuid, 0);
378
379         if (flags & SS_AUTO) {
380                 scrub->os_full_speed = 1;
381                 sf->sf_flags |= SF_AUTO;
382         } else {
383                 scrub->os_full_speed = 0;
384         }
385
386         if (sf->sf_flags & (SF_RECREATED | SF_INCONSISTENT | SF_UPGRADE))
387                 scrub->os_full_speed = 1;
388
389         scrub->os_in_prior = 0;
390         scrub->os_waiting = 0;
391         scrub->os_paused = 0;
392         scrub->os_new_checked = 0;
393         if (sf->sf_pos_last_checkpoint != 0)
394                 sf->sf_pos_latest_start = sf->sf_pos_last_checkpoint + 1;
395         else
396                 sf->sf_pos_latest_start = LDISKFS_FIRST_INO(osd_sb(dev)) + 1;
397
398         scrub->os_pos_current = sf->sf_pos_latest_start;
399         sf->sf_status = SS_SCANNING;
400         sf->sf_time_latest_start = cfs_time_current_sec();
401         sf->sf_time_last_checkpoint = sf->sf_time_latest_start;
402         rc = osd_scrub_file_store(scrub);
403         if (rc == 0) {
404                 spin_lock(&scrub->os_lock);
405                 thread_set_flags(thread, SVC_RUNNING);
406                 spin_unlock(&scrub->os_lock);
407                 cfs_waitq_broadcast(&thread->t_ctl_waitq);
408         }
409         up_write(&scrub->os_rwsem);
410
411         RETURN(rc);
412 }
413
414 static int
415 osd_scrub_check_update(struct osd_thread_info *info, struct osd_device *dev,
416                        struct osd_idmap_cache *oic, int val)
417 {
418         struct osd_scrub             *scrub  = &dev->od_scrub;
419         struct scrub_file            *sf     = &scrub->os_file;
420         struct lu_fid                *fid    = &oic->oic_fid;
421         struct osd_inode_id          *lid    = &oic->oic_lid;
422         struct osd_inode_id          *lid2   = &info->oti_id;
423         struct osd_inconsistent_item *oii    = NULL;
424         struct inode                 *inode  = NULL;
425         int                           ops    = DTO_INDEX_UPDATE;
426         int                           idx;
427         int                           rc;
428         ENTRY;
429
430         down_write(&scrub->os_rwsem);
431         scrub->os_new_checked++;
432         if (val < 0)
433                 GOTO(out, rc = val);
434
435         if (scrub->os_in_prior)
436                 oii = cfs_list_entry(oic, struct osd_inconsistent_item,
437                                      oii_cache);
438
439         if (lid->oii_ino < sf->sf_pos_latest_start && oii == NULL)
440                 GOTO(out, rc = 0);
441
442         if (fid_is_igif(fid))
443                 sf->sf_items_igif++;
444
445         if ((val == SCRUB_NEXT_NOLMA) &&
446             (!dev->od_handle_nolma || OBD_FAIL_CHECK(OBD_FAIL_FID_NOLMA)))
447                 GOTO(out, rc = 0);
448
449         if ((oii != NULL && oii->oii_insert) || (val == SCRUB_NEXT_NOLMA))
450                 goto iget;
451
452         /* XXX: Currently, no FID-in-LMA for OST object, so osd_oi_lookup()
453          *      without checking FLD is enough.
454          *
455          *      It should be updated if FID-in-LMA for OSD object introduced
456          *      in the future. */
457         rc = osd_oi_lookup(info, dev, fid, lid2, false);
458         if (rc != 0) {
459                 if (rc != -ENOENT)
460                         GOTO(out, rc);
461
462 iget:
463                 inode = osd_iget(info, dev, lid);
464                 if (IS_ERR(inode)) {
465                         rc = PTR_ERR(inode);
466                         /* Someone removed the inode. */
467                         if (rc == -ENOENT || rc == -ESTALE)
468                                 rc = 0;
469                         GOTO(out, rc);
470                 }
471
472                 /* Check whether the inode to be unlinked during OI scrub. */
473                 if (unlikely(inode->i_nlink == 0)) {
474                         iput(inode);
475                         GOTO(out, rc = 0);
476                 }
477
478                 ops = DTO_INDEX_INSERT;
479                 idx = osd_oi_fid2idx(dev, fid);
480                 if (val == SCRUB_NEXT_NOLMA) {
481                         sf->sf_flags |= SF_UPGRADE;
482                         scrub->os_full_speed = 1;
483                         rc = osd_ea_fid_set(info, inode, fid, 0);
484                         if (rc != 0)
485                                 GOTO(out, rc);
486
487                         if (!(sf->sf_flags & SF_INCONSISTENT))
488                                 dev->od_igif_inoi = 0;
489                 } else {
490                         sf->sf_flags |= SF_RECREATED;
491                         scrub->os_full_speed = 1;
492                         if (unlikely(!ldiskfs_test_bit(idx, sf->sf_oi_bitmap)))
493                                 ldiskfs_set_bit(idx, sf->sf_oi_bitmap);
494                 }
495         } else if (osd_id_eq(lid, lid2)) {
496                 GOTO(out, rc = 0);
497         } else {
498                 sf->sf_flags |= SF_INCONSISTENT;
499                 scrub->os_full_speed = 1;
500
501                 /* XXX: If the device is restored from file-level backup, then
502                  *      some IGIFs may have been already in OI files, and some
503                  *      may be not yet. Means upgrading from 1.8 may be partly
504                  *      processed, but some clients may hold some immobilized
505                  *      IGIFs, and use them to access related objects. Under
506                  *      such case, OSD does not know whether an given IGIF has
507                  *      been processed or to be processed, and it also cannot
508                  *      generate local ino#/gen# directly from the immobilized
509                  *      IGIF because of the backup/restore. Then force OSD to
510                  *      lookup the given IGIF in OI files, and if no entry,
511                  *      then ask the client to retry after upgrading completed.
512                  *      No better choice. */
513                 dev->od_igif_inoi = 1;
514         }
515
516         rc = osd_scrub_refresh_mapping(info, dev, fid, lid, ops);
517         if (rc == 0) {
518                 if (scrub->os_in_prior)
519                         sf->sf_items_updated_prior++;
520                 else
521                         sf->sf_items_updated++;
522         }
523
524         GOTO(out, rc);
525
526 out:
527         if (rc < 0) {
528                 sf->sf_items_failed++;
529                 if (sf->sf_pos_first_inconsistent == 0 ||
530                     sf->sf_pos_first_inconsistent > lid->oii_ino)
531                         sf->sf_pos_first_inconsistent = lid->oii_ino;
532         } else {
533                 rc = 0;
534         }
535
536         if (ops == DTO_INDEX_INSERT) {
537                 /* There may be conflict unlink during the OI scrub,
538                  * if happend, then remove the new added OI mapping. */
539                 if (unlikely(inode->i_nlink == 0))
540                         osd_scrub_refresh_mapping(info, dev, fid, lid,
541                                                   DTO_INDEX_DELETE);
542                 iput(inode);
543         }
544         up_write(&scrub->os_rwsem);
545
546         if (oii != NULL) {
547                 LASSERT(!cfs_list_empty(&oii->oii_list));
548
549                 spin_lock(&scrub->os_lock);
550                 cfs_list_del_init(&oii->oii_list);
551                 spin_unlock(&scrub->os_lock);
552                 OBD_FREE_PTR(oii);
553         }
554         RETURN(sf->sf_param & SP_FAILOUT ? rc : 0);
555 }
556
557 static int osd_scrub_checkpoint(struct osd_scrub *scrub)
558 {
559         struct scrub_file *sf = &scrub->os_file;
560         int                rc;
561
562         if (likely(cfs_time_before(cfs_time_current(),
563                                    scrub->os_time_next_checkpoint) ||
564                    scrub->os_new_checked == 0))
565                 return 0;
566
567         down_write(&scrub->os_rwsem);
568         sf->sf_items_checked += scrub->os_new_checked;
569         scrub->os_new_checked = 0;
570         sf->sf_pos_last_checkpoint = scrub->os_pos_current;
571         sf->sf_time_last_checkpoint = cfs_time_current_sec();
572         sf->sf_run_time += cfs_duration_sec(cfs_time_current() + HALF_SEC -
573                                             scrub->os_time_last_checkpoint);
574         rc = osd_scrub_file_store(scrub);
575         up_write(&scrub->os_rwsem);
576
577         return rc;
578 }
579
580 static void osd_scrub_post(struct osd_scrub *scrub, int result)
581 {
582         struct scrub_file *sf = &scrub->os_file;
583         ENTRY;
584
585         down_write(&scrub->os_rwsem);
586         spin_lock(&scrub->os_lock);
587         thread_set_flags(&scrub->os_thread, SVC_STOPPING);
588         spin_unlock(&scrub->os_lock);
589         if (scrub->os_new_checked > 0) {
590                 sf->sf_items_checked += scrub->os_new_checked;
591                 scrub->os_new_checked = 0;
592                 sf->sf_pos_last_checkpoint = scrub->os_pos_current;
593         }
594         sf->sf_time_last_checkpoint = cfs_time_current_sec();
595         if (result > 0) {
596                 struct osd_device *dev =
597                         container_of0(scrub, struct osd_device, od_scrub);
598
599                 dev->od_igif_inoi = 1;
600                 sf->sf_status = SS_COMPLETED;
601                 memset(sf->sf_oi_bitmap, 0, SCRUB_OI_BITMAP_SIZE);
602                 sf->sf_flags &= ~(SF_RECREATED | SF_INCONSISTENT |
603                                   SF_UPGRADE | SF_AUTO);
604                 sf->sf_time_last_complete = sf->sf_time_last_checkpoint;
605                 sf->sf_success_count++;
606         } else if (result == 0) {
607                 if (scrub->os_paused)
608                         sf->sf_status = SS_PAUSED;
609                 else
610                         sf->sf_status = SS_STOPPED;
611         } else {
612                 sf->sf_status = SS_FAILED;
613         }
614         sf->sf_run_time += cfs_duration_sec(cfs_time_current() + HALF_SEC -
615                                             scrub->os_time_last_checkpoint);
616         result = osd_scrub_file_store(scrub);
617         if (result < 0)
618                 CERROR("%.16s: fail to osd_scrub_post, rc = %d\n",
619                        LDISKFS_SB(osd_scrub2sb(scrub))->s_es->s_volume_name,
620                        result);
621         up_write(&scrub->os_rwsem);
622
623         EXIT;
624 }
625
626 /* iteration engine */
627
628 struct osd_iit_param {
629         struct super_block *sb;
630         struct buffer_head *bitmap;
631         ldiskfs_group_t bg;
632         __u32 gbase;
633         __u32 offset;
634 };
635
636 typedef int (*osd_iit_next_policy)(struct osd_thread_info *info,
637                                    struct osd_device *dev,
638                                    struct osd_iit_param *param,
639                                    struct osd_idmap_cache **oic,
640                                    int noslot);
641
642 typedef int (*osd_iit_exec_policy)(struct osd_thread_info *info,
643                                    struct osd_device *dev,
644                                    struct osd_iit_param *param,
645                                    struct osd_idmap_cache *oic,
646                                    int *noslot, int rc);
647
648 static int osd_iit_next(struct osd_iit_param *param, __u32 *pos)
649 {
650         param->offset = ldiskfs_find_next_bit(param->bitmap->b_data,
651                         LDISKFS_INODES_PER_GROUP(param->sb), param->offset);
652         if (param->offset >= LDISKFS_INODES_PER_GROUP(param->sb)) {
653                 *pos = 1 + (param->bg+1) * LDISKFS_INODES_PER_GROUP(param->sb);
654                 return SCRUB_NEXT_BREAK;
655         } else {
656                 *pos = param->gbase + param->offset;
657                 return 0;
658         }
659 }
660
661 static int osd_iit_iget(struct osd_thread_info *info, struct osd_device *dev,
662                         struct lu_fid *fid, struct osd_inode_id *lid, __u32 pos,
663                         struct super_block *sb, bool scrub)
664 {
665         struct lustre_mdt_attrs *lma   = &info->oti_mdt_attrs;
666         struct inode            *inode;
667         int                      rc;
668
669         osd_id_gen(lid, pos, OSD_OII_NOGEN);
670         inode = osd_iget(info, dev, lid);
671         if (IS_ERR(inode)) {
672                 rc = PTR_ERR(inode);
673                 /* The inode may be removed after bitmap searching, or the
674                  * file is new created without inode initialized yet. */
675                 if (rc == -ENOENT || rc == -ESTALE)
676                         return SCRUB_NEXT_CONTINUE;
677
678                 CERROR("%.16s: fail to read inode, ino# = %u, rc = %d\n",
679                        LDISKFS_SB(sb)->s_es->s_volume_name, pos, rc);
680                 return rc;
681         }
682
683         /* If the inode has no OI mapping, then it is special locally used,
684          * should be invisible to OI scrub or up layer LFSCK. */
685         if (ldiskfs_test_inode_state(inode, LDISKFS_STATE_LUSTRE_NO_OI)) {
686                 iput(inode);
687                 return SCRUB_NEXT_CONTINUE;
688         }
689
690         if (scrub &&
691             ldiskfs_test_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB)) {
692                 /* Only skip it for the first OI scrub accessing. */
693                 ldiskfs_clear_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
694                 iput(inode);
695                 return SCRUB_NEXT_NOSCRUB;
696         }
697
698         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
699         if (rc == 0) {
700                 if (fid_is_llog(&lma->lma_self_fid) ||
701                     (!scrub && fid_is_internal(&lma->lma_self_fid)) ||
702                     (scrub && (lma->lma_incompat & LMAI_AGENT)))
703                         rc = SCRUB_NEXT_CONTINUE;
704                 else
705                         *fid = lma->lma_self_fid;
706         } else if (rc == -ENODATA) {
707                 lu_igif_build(fid, inode->i_ino, inode->i_generation);
708                 if (scrub)
709                         rc = SCRUB_NEXT_NOLMA;
710                 else
711                         rc = 0;
712         }
713         iput(inode);
714         return rc;
715 }
716
717 static int osd_scrub_next(struct osd_thread_info *info, struct osd_device *dev,
718                           struct osd_iit_param *param,
719                           struct osd_idmap_cache **oic, int noslot)
720 {
721         struct osd_scrub     *scrub  = &dev->od_scrub;
722         struct ptlrpc_thread *thread = &scrub->os_thread;
723         struct lu_fid        *fid;
724         struct osd_inode_id  *lid;
725         int                   rc;
726
727         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_SCRUB_DELAY) && cfs_fail_val > 0) {
728                 struct l_wait_info lwi;
729
730                 lwi = LWI_TIMEOUT(cfs_time_seconds(cfs_fail_val), NULL, NULL);
731                 l_wait_event(thread->t_ctl_waitq,
732                              !cfs_list_empty(&scrub->os_inconsistent_items) ||
733                              !thread_is_running(thread),
734                              &lwi);
735         }
736
737         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_SCRUB_CRASH)) {
738                 spin_lock(&scrub->os_lock);
739                 thread_set_flags(thread, SVC_STOPPING);
740                 spin_unlock(&scrub->os_lock);
741                 return SCRUB_NEXT_CRASH;
742         }
743
744         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_SCRUB_FATAL))
745                 return SCRUB_NEXT_FATAL;
746
747         if (unlikely(!thread_is_running(thread)))
748                 return SCRUB_NEXT_EXIT;
749
750         if (!cfs_list_empty(&scrub->os_inconsistent_items)) {
751                 struct osd_inconsistent_item *oii;
752
753                 oii = cfs_list_entry(scrub->os_inconsistent_items.next,
754                                      struct osd_inconsistent_item, oii_list);
755                 *oic = &oii->oii_cache;
756                 scrub->os_in_prior = 1;
757                 return 0;
758         }
759
760         if (noslot != 0)
761                 return SCRUB_NEXT_WAIT;
762
763         rc = osd_iit_next(param, &scrub->os_pos_current);
764         if (rc != 0)
765                 return rc;
766
767         *oic = &scrub->os_oic;
768         fid = &(*oic)->oic_fid;
769         lid = &(*oic)->oic_lid;
770         rc = osd_iit_iget(info, dev, fid, lid,
771                           scrub->os_pos_current, param->sb, true);
772         return rc;
773 }
774
775 static int osd_preload_next(struct osd_thread_info *info,
776                             struct osd_device *dev, struct osd_iit_param *param,
777                             struct osd_idmap_cache **oic, int noslot)
778 {
779         struct osd_otable_cache *ooc    = &dev->od_otable_it->ooi_cache;
780         struct osd_scrub        *scrub;
781         struct ptlrpc_thread    *thread;
782         int                      rc;
783
784         rc = osd_iit_next(param, &ooc->ooc_pos_preload);
785         if (rc != 0)
786                 return rc;
787
788         scrub = &dev->od_scrub;
789         thread = &scrub->os_thread;
790         if (thread_is_running(thread) &&
791             ooc->ooc_pos_preload >= scrub->os_pos_current)
792                 return SCRUB_NEXT_EXIT;
793
794         rc = osd_iit_iget(info, dev,
795                           &ooc->ooc_cache[ooc->ooc_producer_idx].oic_fid,
796                           &ooc->ooc_cache[ooc->ooc_producer_idx].oic_lid,
797                           ooc->ooc_pos_preload, param->sb, false);
798         /* If succeed, it needs to move forward; otherwise up layer LFSCK may
799          * ignore the failure, so it still need to skip the inode next time. */
800         ooc->ooc_pos_preload = param->gbase + ++(param->offset);
801         return rc;
802 }
803
804 static inline int
805 osd_scrub_wakeup(struct osd_scrub *scrub, struct osd_otable_it *it)
806 {
807         spin_lock(&scrub->os_lock);
808         if (osd_scrub_has_window(scrub, &it->ooi_cache) ||
809             !cfs_list_empty(&scrub->os_inconsistent_items) ||
810             it->ooi_waiting || !thread_is_running(&scrub->os_thread))
811                 scrub->os_waiting = 0;
812         else
813                 scrub->os_waiting = 1;
814         spin_unlock(&scrub->os_lock);
815
816         return !scrub->os_waiting;
817 }
818
819 static int osd_scrub_exec(struct osd_thread_info *info, struct osd_device *dev,
820                           struct osd_iit_param *param,
821                           struct osd_idmap_cache *oic, int *noslot, int rc)
822 {
823         struct l_wait_info       lwi    = { 0 };
824         struct osd_scrub        *scrub  = &dev->od_scrub;
825         struct scrub_file       *sf     = &scrub->os_file;
826         struct ptlrpc_thread    *thread = &scrub->os_thread;
827         struct osd_otable_it    *it     = dev->od_otable_it;
828         struct osd_otable_cache *ooc    = it ? &it->ooi_cache : NULL;
829
830         switch (rc) {
831         case SCRUB_NEXT_CONTINUE:
832                 goto next;
833         case SCRUB_NEXT_WAIT:
834                 goto wait;
835         case SCRUB_NEXT_NOSCRUB:
836                 down_write(&scrub->os_rwsem);
837                 scrub->os_new_checked++;
838                 sf->sf_items_noscrub++;
839                 up_write(&scrub->os_rwsem);
840                 goto next;
841         }
842
843         rc = osd_scrub_check_update(info, dev, oic, rc);
844         if (rc != 0)
845                 return rc;
846
847         rc = osd_scrub_checkpoint(scrub);
848         if (rc != 0) {
849                 CERROR("%.16s: fail to checkpoint, pos = %u, rc = %d\n",
850                        LDISKFS_SB(param->sb)->s_es->s_volume_name,
851                        scrub->os_pos_current, rc);
852                 /* Continue, as long as the scrub itself can go ahead. */
853         }
854
855         if (scrub->os_in_prior) {
856                 scrub->os_in_prior = 0;
857                 return 0;
858         }
859
860 next:
861         scrub->os_pos_current = param->gbase + ++(param->offset);
862
863 wait:
864         if (it != NULL && it->ooi_waiting &&
865             ooc->ooc_pos_preload < scrub->os_pos_current) {
866                 spin_lock(&scrub->os_lock);
867                 it->ooi_waiting = 0;
868                 cfs_waitq_broadcast(&thread->t_ctl_waitq);
869                 spin_unlock(&scrub->os_lock);
870         }
871
872         if (scrub->os_full_speed || rc == SCRUB_NEXT_CONTINUE)
873                 return 0;
874
875         if (osd_scrub_has_window(scrub, ooc)) {
876                 *noslot = 0;
877                 return 0;
878         }
879
880         l_wait_event(thread->t_ctl_waitq,
881                      osd_scrub_wakeup(scrub, it),
882                      &lwi);
883
884         if (osd_scrub_has_window(scrub, ooc))
885                 *noslot = 0;
886         else
887                 *noslot = 1;
888         return 0;
889 }
890
891 static int osd_preload_exec(struct osd_thread_info *info,
892                             struct osd_device *dev, struct osd_iit_param *param,
893                             struct osd_idmap_cache *oic, int *noslot, int rc)
894 {
895         struct osd_otable_cache *ooc = &dev->od_otable_it->ooi_cache;
896
897         if (rc == 0) {
898                 ooc->ooc_cached_items++;
899                 ooc->ooc_producer_idx = (ooc->ooc_producer_idx + 1) &
900                                         ~OSD_OTABLE_IT_CACHE_MASK;
901         }
902         return rc > 0 ? 0 : rc;
903 }
904
905 #define SCRUB_IT_ALL    1
906 #define SCRUB_IT_CRASH  2
907
908 static int osd_inode_iteration(struct osd_thread_info *info,
909                                struct osd_device *dev, __u32 max, bool preload)
910 {
911         osd_iit_next_policy   next;
912         osd_iit_exec_policy   exec;
913         __u32                *pos;
914         __u32                *count;
915         struct osd_iit_param  param;
916         __u32                 limit;
917         int                   noslot = 0;
918         int                   rc;
919         ENTRY;
920
921         if (!preload) {
922                 struct osd_scrub *scrub = &dev->od_scrub;
923
924                 next = osd_scrub_next;
925                 exec = osd_scrub_exec;
926                 pos = &scrub->os_pos_current;
927                 count = &scrub->os_new_checked;
928         } else {
929                 struct osd_otable_cache *ooc = &dev->od_otable_it->ooi_cache;
930
931                 next = osd_preload_next;
932                 exec = osd_preload_exec;
933                 pos = &ooc->ooc_pos_preload;
934                 count = &ooc->ooc_cached_items;
935         }
936         param.sb = osd_sb(dev);
937         limit = le32_to_cpu(LDISKFS_SB(param.sb)->s_es->s_inodes_count);
938
939         while (*pos <= limit && *count < max) {
940                 struct osd_idmap_cache *oic = NULL;
941
942                 param.bg = (*pos - 1) / LDISKFS_INODES_PER_GROUP(param.sb);
943                 param.offset = (*pos - 1) % LDISKFS_INODES_PER_GROUP(param.sb);
944                 param.gbase = 1 + param.bg * LDISKFS_INODES_PER_GROUP(param.sb);
945                 param.bitmap = ldiskfs_read_inode_bitmap(param.sb, param.bg);
946                 if (param.bitmap == NULL) {
947                         CERROR("%.16s: fail to read bitmap for %u, "
948                                "scrub will stop, urgent mode\n",
949                                LDISKFS_SB(param.sb)->s_es->s_volume_name,
950                                (__u32)param.bg);
951                         RETURN(-EIO);
952                 }
953
954                 while (param.offset < LDISKFS_INODES_PER_GROUP(param.sb) &&
955                        *count < max) {
956                         rc = next(info, dev, &param, &oic, noslot);
957                         switch (rc) {
958                         case SCRUB_NEXT_BREAK:
959                                 goto next_group;
960                         case SCRUB_NEXT_EXIT:
961                                 brelse(param.bitmap);
962                                 RETURN(0);
963                         case SCRUB_NEXT_CRASH:
964                                 brelse(param.bitmap);
965                                 RETURN(SCRUB_IT_CRASH);
966                         case SCRUB_NEXT_FATAL:
967                                 brelse(param.bitmap);
968                                 RETURN(-EINVAL);
969                         }
970
971                         rc = exec(info, dev, &param, oic, &noslot, rc);
972                         if (rc != 0) {
973                                 brelse(param.bitmap);
974                                 RETURN(rc);
975                         }
976                 }
977
978 next_group:
979                 brelse(param.bitmap);
980         }
981
982         if (*pos > limit)
983                 RETURN(SCRUB_IT_ALL);
984         RETURN(0);
985 }
986
987 static int osd_otable_it_preload(const struct lu_env *env,
988                                  struct osd_otable_it *it)
989 {
990         struct osd_device       *dev   = it->ooi_dev;
991         struct osd_scrub        *scrub = &dev->od_scrub;
992         struct osd_otable_cache *ooc   = &it->ooi_cache;
993         int                      rc;
994         ENTRY;
995
996         rc = osd_inode_iteration(osd_oti_get(env), dev,
997                                  OSD_OTABLE_IT_CACHE_SIZE, true);
998         if (rc == SCRUB_IT_ALL)
999                 it->ooi_all_cached = 1;
1000
1001         CDEBUG(D_LFSCK, "OSD pre-loaded: max = %u, preload = %u, rc = %d\n",
1002                le32_to_cpu(LDISKFS_SB(osd_sb(dev))->s_es->s_inodes_count),
1003                ooc->ooc_pos_preload, rc);
1004
1005         if (scrub->os_waiting && osd_scrub_has_window(scrub, ooc)) {
1006                 scrub->os_waiting = 0;
1007                 cfs_waitq_broadcast(&scrub->os_thread.t_ctl_waitq);
1008         }
1009
1010         RETURN(rc < 0 ? rc : ooc->ooc_cached_items);
1011 }
1012
1013 static int osd_scrub_main(void *args)
1014 {
1015         struct lu_env         env;
1016         struct osd_device    *dev    = (struct osd_device *)args;
1017         struct osd_scrub     *scrub  = &dev->od_scrub;
1018         struct ptlrpc_thread *thread = &scrub->os_thread;
1019         struct super_block   *sb     = osd_sb(dev);
1020         int                   rc;
1021         ENTRY;
1022
1023         cfs_daemonize("OI_scrub");
1024         rc = lu_env_init(&env, LCT_DT_THREAD);
1025         if (rc != 0) {
1026                 CERROR("%.16s: OI scrub, fail to init env, rc = %d\n",
1027                        LDISKFS_SB(sb)->s_es->s_volume_name, rc);
1028                 GOTO(noenv, rc);
1029         }
1030
1031         rc = osd_scrub_prep(dev);
1032         if (rc != 0) {
1033                 CERROR("%.16s: OI scrub, fail to scrub prep, rc = %d\n",
1034                        LDISKFS_SB(sb)->s_es->s_volume_name, rc);
1035                 GOTO(out, rc);
1036         }
1037
1038         if (!scrub->os_full_speed) {
1039                 struct l_wait_info lwi = { 0 };
1040                 struct osd_otable_it *it = dev->od_otable_it;
1041                 struct osd_otable_cache *ooc = &it->ooi_cache;
1042
1043                 l_wait_event(thread->t_ctl_waitq,
1044                              it->ooi_user_ready || !thread_is_running(thread),
1045                              &lwi);
1046                 if (unlikely(!thread_is_running(thread)))
1047                         GOTO(post, rc = 0);
1048
1049                 scrub->os_pos_current = ooc->ooc_pos_preload;
1050         }
1051
1052         CDEBUG(D_LFSCK, "OI scrub: flags = 0x%x, pos = %u\n",
1053                scrub->os_start_flags, scrub->os_pos_current);
1054
1055         rc = osd_inode_iteration(osd_oti_get(&env), dev, ~0U, false);
1056         if (unlikely(rc == SCRUB_IT_CRASH))
1057                 GOTO(out, rc = -EINVAL);
1058         GOTO(post, rc);
1059
1060 post:
1061         osd_scrub_post(scrub, rc);
1062         CDEBUG(D_LFSCK, "OI scrub: stop, rc = %d, pos = %u\n",
1063                rc, scrub->os_pos_current);
1064
1065 out:
1066         while (!cfs_list_empty(&scrub->os_inconsistent_items)) {
1067                 struct osd_inconsistent_item *oii;
1068
1069                 oii = cfs_list_entry(scrub->os_inconsistent_items.next,
1070                                      struct osd_inconsistent_item, oii_list);
1071                 cfs_list_del_init(&oii->oii_list);
1072                 OBD_FREE_PTR(oii);
1073         }
1074         lu_env_fini(&env);
1075
1076 noenv:
1077         spin_lock(&scrub->os_lock);
1078         thread_set_flags(thread, SVC_STOPPED);
1079         cfs_waitq_broadcast(&thread->t_ctl_waitq);
1080         spin_unlock(&scrub->os_lock);
1081         return rc;
1082 }
1083
1084 /* initial OI scrub */
1085
1086 typedef int (*scandir_t)(struct osd_thread_info *, struct osd_device *,
1087                          struct dentry *, filldir_t filldir);
1088
1089 static int osd_ios_varfid_fill(void *buf, const char *name, int namelen,
1090                                loff_t offset, __u64 ino, unsigned d_type);
1091
1092 static int
1093 osd_ios_general_scan(struct osd_thread_info *info, struct osd_device *dev,
1094                      struct dentry *dentry, filldir_t filldir);
1095 static int
1096 osd_ios_ROOT_scan(struct osd_thread_info *info, struct osd_device *dev,
1097                   struct dentry *dentry, filldir_t filldir);
1098
1099 static int
1100 osd_ios_OBJECTS_scan(struct osd_thread_info *info, struct osd_device *dev,
1101                      struct dentry *dentry, filldir_t filldir);
1102
1103 enum osd_lf_flags {
1104         OLF_SCAN_SUBITEMS       = 0x0001,
1105         OLF_HIDE_FID            = 0x0002,
1106         OLF_SHOW_NAME           = 0x0004,
1107 };
1108
1109 struct osd_lf_map {
1110         char            *olm_name;
1111         struct lu_fid    olm_fid;
1112         __u16            olm_flags;
1113         scandir_t        olm_scandir;
1114         filldir_t        olm_filldir;
1115 };
1116
1117 /* Add the new introduced local files in the list in the future. */
1118 static const struct osd_lf_map osd_lf_maps[] = {
1119         /* CATALOGS */
1120         { CATLIST, { FID_SEQ_LOCAL_FILE, LLOG_CATALOGS_OID, 0 }, OLF_SHOW_NAME,
1121                 NULL, NULL },
1122
1123         /* CONFIGS */
1124         { MOUNT_CONFIGS_DIR, { FID_SEQ_LOCAL_FILE, MGS_CONFIGS_OID, 0 },
1125                 OLF_SCAN_SUBITEMS, osd_ios_general_scan,
1126                 osd_ios_varfid_fill },
1127
1128         /* NIDTBL_VERSIONS */
1129         { MGS_NIDTBL_DIR, { 0, 0, 0 }, OLF_SCAN_SUBITEMS,
1130                 osd_ios_general_scan, osd_ios_varfid_fill },
1131
1132         /* PENDING */
1133         { "PENDING", { 0, 0, 0 }, 0, NULL, NULL },
1134
1135         /* ROOT */
1136         { "ROOT", { FID_SEQ_ROOT, 1, 0 },
1137                 OLF_SCAN_SUBITEMS | OLF_HIDE_FID, osd_ios_ROOT_scan, NULL },
1138
1139         /* changelog_catalog */
1140         { CHANGELOG_CATALOG, { 0, 0, 0 }, 0, NULL, NULL },
1141
1142         /* changelog_users */
1143         { CHANGELOG_USERS, { 0, 0, 0 }, 0, NULL, NULL },
1144
1145         /* fld */
1146         { "fld", { FID_SEQ_LOCAL_FILE, FLD_INDEX_OID, 0 }, OLF_SHOW_NAME,
1147                 NULL, NULL },
1148
1149         /* last_rcvd */
1150         { LAST_RCVD, { FID_SEQ_LOCAL_FILE, LAST_RECV_OID, 0 }, OLF_SHOW_NAME,
1151                 NULL, NULL },
1152
1153         /* lfsck_bookmark */
1154         { "lfsck_bookmark", { 0, 0, 0 }, 0, NULL, NULL },
1155
1156         /* lov_objid */
1157         { LOV_OBJID, { FID_SEQ_LOCAL_FILE, MDD_LOV_OBJ_OID, 0 }, OLF_SHOW_NAME,
1158                 NULL, NULL },
1159
1160         /* lov_objseq */
1161         { LOV_OBJSEQ, { FID_SEQ_LOCAL_FILE, MDD_LOV_OBJ_OSEQ, 0 },
1162                 OLF_SHOW_NAME, NULL, NULL },
1163
1164         /* quota_master */
1165         { QMT_DIR, { 0, 0, 0 }, OLF_SCAN_SUBITEMS,
1166                 osd_ios_general_scan, osd_ios_varfid_fill },
1167
1168         /* quota_slave */
1169         { QSD_DIR, { 0, 0, 0 }, OLF_SCAN_SUBITEMS,
1170                 osd_ios_general_scan, osd_ios_varfid_fill },
1171
1172         /* seq_ctl */
1173         { "seq_ctl", { FID_SEQ_LOCAL_FILE, FID_SEQ_CTL_OID, 0 },
1174                 OLF_SHOW_NAME, NULL, NULL },
1175
1176         /* seq_srv */
1177         { "seq_srv", { FID_SEQ_LOCAL_FILE, FID_SEQ_SRV_OID, 0 },
1178                 OLF_SHOW_NAME, NULL, NULL },
1179
1180         /* health_check */
1181         { HEALTH_CHECK, { FID_SEQ_LOCAL_FILE, OFD_HEALTH_CHECK_OID, 0 },
1182                 OLF_SHOW_NAME, NULL, NULL },
1183
1184         /* lfsck_namespace */
1185         { "lfsck_namespace", { 0, 0, 0 }, 0, NULL, NULL },
1186
1187         /* OBJECTS, upgrade from old device */
1188         { OBJECTS, { 0, 0, 0 }, OLF_SCAN_SUBITEMS, osd_ios_OBJECTS_scan, NULL },
1189
1190         /* lquota_v2.user, upgrade from old device */
1191         { "lquota_v2.user", { 0, 0, 0 }, 0, NULL, NULL },
1192
1193         /* lquota_v2.group, upgrade from old device */
1194         { "lquota_v2.group", { 0, 0, 0 }, 0, NULL, NULL },
1195
1196         /* LAST_GROUP, upgrade from old device */
1197         { "LAST_GROUP", { FID_SEQ_LOCAL_FILE, OFD_LAST_GROUP_OID, 0 },
1198                 OLF_SHOW_NAME, NULL, NULL },
1199
1200         { NULL, { 0, 0, 0 }, 0, NULL, NULL }
1201 };
1202
1203 struct osd_ios_item {
1204         cfs_list_t       oii_list;
1205         struct dentry   *oii_dentry;
1206         scandir_t        oii_scandir;
1207         filldir_t        oii_filldir;
1208 };
1209
1210 struct osd_ios_filldir_buf {
1211         struct osd_thread_info  *oifb_info;
1212         struct osd_device       *oifb_dev;
1213         struct dentry           *oifb_dentry;
1214 };
1215
1216 static inline struct dentry *
1217 osd_ios_lookup_one_len(const char *name, struct dentry *parent, int namelen)
1218 {
1219         struct dentry *dentry;
1220
1221         dentry = ll_lookup_one_len(name, parent, namelen);
1222         if (!IS_ERR(dentry) && dentry->d_inode == NULL) {
1223                 dput(dentry);
1224                 return ERR_PTR(-ENOENT);
1225         }
1226
1227         return dentry;
1228 }
1229
1230 static inline void
1231 osd_ios_llogname2fid(struct lu_fid *fid, const char *name, int namelen)
1232 {
1233         obd_id id = 0;
1234         int    i  = 0;
1235
1236         fid->f_seq = FID_SEQ_LLOG;
1237         while (i < namelen)
1238                 id = id * 10 + name[i++] - '0';
1239
1240         fid->f_oid = id & 0x00000000ffffffffULL;
1241         fid->f_ver = id >> 32;
1242 }
1243
1244 static inline void
1245 osd_ios_Oname2fid(struct lu_fid *fid, const char *name, int namelen)
1246 {
1247         __u64 seq = 0;
1248         int   i   = 0;
1249
1250         while (i < namelen)
1251                 seq = seq * 10 + name[i++] - '0';
1252
1253         lu_last_id_fid(fid, seq);
1254 }
1255
1256 static int
1257 osd_ios_new_item(struct osd_device *dev, struct dentry *dentry,
1258                  scandir_t scandir, filldir_t filldir)
1259 {
1260         struct osd_ios_item *item;
1261
1262         OBD_ALLOC_PTR(item);
1263         if (item == NULL)
1264                 return -ENOMEM;
1265
1266         CFS_INIT_LIST_HEAD(&item->oii_list);
1267         item->oii_dentry = dget(dentry);
1268         item->oii_scandir = scandir;
1269         item->oii_filldir = filldir;
1270         cfs_list_add_tail(&item->oii_list, &dev->od_ios_list);
1271         return 0;
1272 }
1273
1274 /**
1275  * osd_ios_scan_one() - check/fix LMA FID and OI entry for one inode
1276  *
1277  * The passed \a inode's \a fid is verified against the LMA FID. If the \a fid
1278  * is NULL or is empty the IGIF FID is used. The FID is verified in the OI to
1279  * reference the inode, or fixed if it is missing or references another inode.
1280  */
1281 static int
1282 osd_ios_scan_one(struct osd_thread_info *info, struct osd_device *dev,
1283                  struct inode *inode, const struct lu_fid *fid, int flags)
1284 {
1285         struct lustre_mdt_attrs *lma    = &info->oti_mdt_attrs;
1286         struct osd_inode_id     *id     = &info->oti_id;
1287         struct osd_inode_id     *id2    = &info->oti_id2;
1288         struct osd_scrub        *scrub  = &dev->od_scrub;
1289         struct scrub_file       *sf     = &scrub->os_file;
1290         struct lu_fid            tfid;
1291         int                      rc;
1292         ENTRY;
1293
1294         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
1295         if (rc != 0 && rc != -ENODATA)
1296                 RETURN(rc);
1297
1298         osd_id_gen(id, inode->i_ino, inode->i_generation);
1299         if (rc == -ENODATA) {
1300                 if (fid == NULL || fid_is_zero(fid) || flags & OLF_HIDE_FID)
1301                         lu_igif_build(&tfid, inode->i_ino, inode->i_generation);
1302                 else
1303                         tfid = *fid;
1304                 rc = osd_ea_fid_set(info, inode, &tfid, 0);
1305                 if (rc != 0)
1306                         RETURN(rc);
1307         } else {
1308                 tfid = lma->lma_self_fid;
1309         }
1310
1311         rc = __osd_oi_lookup(info, dev, &tfid, id2);
1312         if (rc != 0) {
1313                 if (rc != -ENOENT)
1314                         RETURN(rc);
1315
1316                 rc = osd_scrub_refresh_mapping(info, dev, &tfid, id,
1317                                                DTO_INDEX_INSERT);
1318                 RETURN(rc);
1319         }
1320
1321         if (osd_id_eq_strict(id, id2))
1322                 RETURN(0);
1323
1324         if (!(sf->sf_flags & SF_INCONSISTENT)) {
1325                 osd_scrub_file_reset(scrub,
1326                                      LDISKFS_SB(osd_sb(dev))->s_es->s_uuid,
1327                                      SF_INCONSISTENT);
1328                 rc = osd_scrub_file_store(scrub);
1329                 if (rc != 0)
1330                         RETURN(rc);
1331         }
1332
1333         rc = osd_scrub_refresh_mapping(info, dev, &tfid, id, DTO_INDEX_UPDATE);
1334
1335         RETURN(rc);
1336 }
1337
1338 static int osd_ios_varfid_fill(void *buf, const char *name, int namelen,
1339                                loff_t offset, __u64 ino, unsigned d_type)
1340 {
1341         struct osd_ios_filldir_buf *fill_buf = buf;
1342         struct osd_device          *dev      = fill_buf->oifb_dev;
1343         struct dentry              *child;
1344         int                         rc;
1345         ENTRY;
1346
1347         /* skip any '.' started names */
1348         if (name[0] == '.')
1349                 RETURN(0);
1350
1351         child = osd_ios_lookup_one_len(name, fill_buf->oifb_dentry, namelen);
1352         if (IS_ERR(child))
1353                 RETURN(PTR_ERR(child));
1354
1355         rc = osd_ios_scan_one(fill_buf->oifb_info, dev, child->d_inode,
1356                               NULL, 0);
1357         if (rc == 0 && S_ISDIR(child->d_inode->i_mode))
1358                 rc = osd_ios_new_item(dev, child, osd_ios_general_scan,
1359                                       osd_ios_varfid_fill);
1360         dput(child);
1361
1362         RETURN(rc);
1363 }
1364
1365 static int osd_ios_root_fill(void *buf, const char *name, int namelen,
1366                              loff_t offset, __u64 ino, unsigned d_type)
1367 {
1368         struct osd_ios_filldir_buf *fill_buf = buf;
1369         struct osd_device          *dev      = fill_buf->oifb_dev;
1370         const struct osd_lf_map    *map;
1371         struct dentry              *child;
1372         int                         rc       = 0;
1373         ENTRY;
1374
1375         /* skip any '.' started names */
1376         if (name[0] == '.')
1377                 RETURN(0);
1378
1379         for (map = osd_lf_maps; map->olm_name != NULL; map++) {
1380                 if (strlen(map->olm_name) != namelen)
1381                         continue;
1382
1383                 if (strncmp(map->olm_name, name, namelen) == 0)
1384                         break;
1385         }
1386
1387         if (map->olm_name == NULL)
1388                 RETURN(0);
1389
1390         child = osd_ios_lookup_one_len(name, fill_buf->oifb_dentry, namelen);
1391         if (IS_ERR(child))
1392                 RETURN(PTR_ERR(child));
1393
1394         rc = osd_ios_scan_one(fill_buf->oifb_info, dev, child->d_inode,
1395                               &map->olm_fid, map->olm_flags);
1396         if (rc == 0 && map->olm_flags & OLF_SCAN_SUBITEMS)
1397                 rc = osd_ios_new_item(dev, child, map->olm_scandir,
1398                                       map->olm_filldir);
1399         dput(child);
1400
1401         RETURN(rc);
1402 }
1403
1404 static int
1405 osd_ios_general_scan(struct osd_thread_info *info, struct osd_device *dev,
1406                      struct dentry *dentry, filldir_t filldir)
1407 {
1408         struct osd_ios_filldir_buf    buf   = { info, dev, dentry };
1409         struct file                  *filp  = &info->oti_it_ea.oie_file;
1410         struct inode                 *inode = dentry->d_inode;
1411         const struct file_operations *fops  = inode->i_fop;
1412         int                           rc;
1413         ENTRY;
1414
1415         LASSERT(filldir != NULL);
1416
1417         filp->f_pos = 0;
1418         filp->f_dentry = dentry;
1419         filp->f_mode = FMODE_64BITHASH;
1420         filp->f_mapping = inode->i_mapping;
1421         filp->f_op = fops;
1422         filp->private_data = NULL;
1423
1424         rc = fops->readdir(filp, &buf, filldir);
1425         fops->release(inode, filp);
1426
1427         RETURN(rc);
1428 }
1429
1430 static int
1431 osd_ios_ROOT_scan(struct osd_thread_info *info, struct osd_device *dev,
1432                   struct dentry *dentry, filldir_t filldir)
1433 {
1434         struct osd_scrub  *scrub  = &dev->od_scrub;
1435         struct scrub_file *sf     = &scrub->os_file;
1436         struct dentry     *child;
1437         int                rc;
1438         ENTRY;
1439
1440         /* It is existing MDT device. */
1441         dev->od_handle_nolma = 1;
1442         child = osd_ios_lookup_one_len(dot_lustre_name, dentry,
1443                                        strlen(dot_lustre_name));
1444         if (IS_ERR(child)) {
1445                 rc = PTR_ERR(child);
1446                 if (rc == -ENOENT) {
1447                         /* It is 1.8 MDT device. */
1448                         if (!(sf->sf_flags & SF_UPGRADE)) {
1449                                 osd_scrub_file_reset(scrub,
1450                                         LDISKFS_SB(osd_sb(dev))->s_es->s_uuid,
1451                                         SF_UPGRADE);
1452                                 rc = osd_scrub_file_store(scrub);
1453                         } else {
1454                                 rc = 0;
1455                         }
1456                 }
1457         } else {
1458                 /* For lustre-2.x (x <= 3), the ".lustre" has NO FID-in-LMA,
1459                  * so the client will get IGIF for the ".lustre" object when
1460                  * the MDT restart.
1461                  *
1462                  * From the OI scrub view, when the MDT upgrade to Lustre-2.4,
1463                  * it does not know whether there are some old clients cached
1464                  * the ".lustre" IGIF during the upgrading. Two choices:
1465                  *
1466                  * 1) Generate IGIF-in-LMA and IGIF-in-OI for the ".lustre".
1467                  *    It will allow the old connected clients to access the
1468                  *    ".lustre" with cached IGIF. But it will cause others
1469                  *    on the MDT failed to check "fid_is_dot_lustre()".
1470                  *
1471                  * 2) Use fixed FID {FID_SEQ_DOT_LUSTRE, FID_OID_DOT_LUSTRE, 0}
1472                  *    for ".lustre" in spite of whether there are some clients
1473                  *    cached the ".lustre" IGIF or not. It enables the check
1474                  *    "fid_is_dot_lustre()" on the MDT, although it will cause
1475                  *    that the old connected clients cannot access the ".lustre"
1476                  *    with the cached IGIF.
1477                  *
1478                  * Usually, it is rare case for the old connected clients
1479                  * to access the ".lustre" with cached IGIF. So we prefer
1480                  * to the solution 2). */
1481                 rc = osd_ios_scan_one(info, dev, child->d_inode,
1482                                       &LU_DOT_LUSTRE_FID, 0);
1483                 dput(child);
1484         }
1485
1486         RETURN(rc);
1487 }
1488
1489 static int
1490 osd_ios_OBJECTS_scan(struct osd_thread_info *info, struct osd_device *dev,
1491                      struct dentry *dentry, filldir_t filldir)
1492 {
1493         struct dentry *child;
1494         int            rc;
1495         ENTRY;
1496
1497         child = osd_ios_lookup_one_len(ADMIN_USR, dentry, strlen(ADMIN_USR));
1498         if (!IS_ERR(child)) {
1499                 rc = osd_ios_scan_one(info, dev, child->d_inode, NULL, 0);
1500                 dput(child);
1501         } else {
1502                 rc = PTR_ERR(child);
1503         }
1504
1505         if (rc != 0 && rc != -ENOENT)
1506                 RETURN(rc);
1507
1508         child = osd_ios_lookup_one_len(ADMIN_GRP, dentry, strlen(ADMIN_GRP));
1509         if (!IS_ERR(child)) {
1510                 rc = osd_ios_scan_one(info, dev, child->d_inode, NULL, 0);
1511                 dput(child);
1512         } else {
1513                 rc = PTR_ERR(child);
1514         }
1515
1516         if (rc == -ENOENT)
1517                 rc = 0;
1518
1519         RETURN(rc);
1520 }
1521
1522 static int osd_initial_OI_scrub(struct osd_thread_info *info,
1523                                 struct osd_device *dev)
1524 {
1525         struct osd_ios_item *item    = NULL;
1526         scandir_t            scandir = osd_ios_general_scan;
1527         filldir_t            filldir = osd_ios_root_fill;
1528         struct dentry       *dentry  = osd_sb(dev)->s_root;
1529         int                  rc;
1530         ENTRY;
1531
1532         while (1) {
1533                 rc = scandir(info, dev, dentry, filldir);
1534                 if (item != NULL) {
1535                         dput(item->oii_dentry);
1536                         OBD_FREE_PTR(item);
1537                 }
1538
1539                 if (rc != 0)
1540                         break;
1541
1542                 if (cfs_list_empty(&dev->od_ios_list))
1543                         break;
1544
1545                 item = cfs_list_entry(dev->od_ios_list.next,
1546                                       struct osd_ios_item, oii_list);
1547                 cfs_list_del_init(&item->oii_list);
1548
1549                 LASSERT(item->oii_scandir != NULL);
1550                 scandir = item->oii_scandir;
1551                 filldir = item->oii_filldir;
1552                 dentry = item->oii_dentry;
1553         }
1554
1555         while (!cfs_list_empty(&dev->od_ios_list)) {
1556                 item = cfs_list_entry(dev->od_ios_list.next,
1557                                       struct osd_ios_item, oii_list);
1558                 cfs_list_del_init(&item->oii_list);
1559                 dput(item->oii_dentry);
1560                 OBD_FREE_PTR(item);
1561         }
1562
1563         RETURN(rc);
1564 }
1565
1566 char *osd_lf_fid2name(const struct lu_fid *fid)
1567 {
1568         const struct osd_lf_map *map = osd_lf_maps;
1569
1570         while (map->olm_name != NULL) {
1571                 if (!lu_fid_eq(fid, &map->olm_fid)) {
1572                         map++;
1573                         continue;
1574                 }
1575
1576                 if (map->olm_flags & OLF_SHOW_NAME)
1577                         return map->olm_name;
1578                 else
1579                         return "";
1580         }
1581
1582         return NULL;
1583 }
1584
1585 /* OI scrub start/stop */
1586
1587 static int do_osd_scrub_start(struct osd_device *dev, __u32 flags)
1588 {
1589         struct osd_scrub     *scrub  = &dev->od_scrub;
1590         struct ptlrpc_thread *thread = &scrub->os_thread;
1591         struct l_wait_info    lwi    = { 0 };
1592         int                   rc;
1593         ENTRY;
1594
1595 again:
1596         /* os_lock: sync status between stop and scrub thread */
1597         spin_lock(&scrub->os_lock);
1598         if (thread_is_running(thread)) {
1599                 spin_unlock(&scrub->os_lock);
1600                 RETURN(-EALREADY);
1601         } else if (unlikely(thread_is_stopping(thread))) {
1602                 spin_unlock(&scrub->os_lock);
1603                 l_wait_event(thread->t_ctl_waitq,
1604                              thread_is_stopped(thread),
1605                              &lwi);
1606                 goto again;
1607         }
1608         spin_unlock(&scrub->os_lock);
1609
1610         if (scrub->os_file.sf_status == SS_COMPLETED)
1611                 flags |= SS_RESET;
1612
1613         scrub->os_start_flags = flags;
1614         thread_set_flags(thread, 0);
1615         rc = cfs_create_thread(osd_scrub_main, dev, 0);
1616         if (rc < 0) {
1617                 CERROR("%.16s: cannot start iteration thread, rc = %d\n",
1618                        LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name, rc);
1619                 RETURN(rc);
1620         }
1621
1622         l_wait_event(thread->t_ctl_waitq,
1623                      thread_is_running(thread) || thread_is_stopped(thread),
1624                      &lwi);
1625
1626         RETURN(0);
1627 }
1628
1629 int osd_scrub_start(struct osd_device *dev)
1630 {
1631         int rc;
1632         ENTRY;
1633
1634         /* od_otable_mutex: prevent curcurrent start/stop */
1635         mutex_lock(&dev->od_otable_mutex);
1636         rc = do_osd_scrub_start(dev, SS_AUTO);
1637         mutex_unlock(&dev->od_otable_mutex);
1638
1639         RETURN(rc == -EALREADY ? 0 : rc);
1640 }
1641
1642 static void do_osd_scrub_stop(struct osd_scrub *scrub)
1643 {
1644         struct ptlrpc_thread *thread = &scrub->os_thread;
1645         struct l_wait_info    lwi    = { 0 };
1646
1647         /* os_lock: sync status between stop and scrub thread */
1648         spin_lock(&scrub->os_lock);
1649         if (!thread_is_init(thread) && !thread_is_stopped(thread)) {
1650                 thread_set_flags(thread, SVC_STOPPING);
1651                 spin_unlock(&scrub->os_lock);
1652                 cfs_waitq_broadcast(&thread->t_ctl_waitq);
1653                 l_wait_event(thread->t_ctl_waitq,
1654                              thread_is_stopped(thread),
1655                              &lwi);
1656                 /* Do not skip the last lock/unlock, which can guarantee that
1657                  * the caller cannot return until the OI scrub thread exit. */
1658                 spin_lock(&scrub->os_lock);
1659         }
1660         spin_unlock(&scrub->os_lock);
1661 }
1662
1663 static void osd_scrub_stop(struct osd_device *dev)
1664 {
1665         /* od_otable_mutex: prevent curcurrent start/stop */
1666         mutex_lock(&dev->od_otable_mutex);
1667         dev->od_scrub.os_paused = 1;
1668         do_osd_scrub_stop(&dev->od_scrub);
1669         mutex_unlock(&dev->od_otable_mutex);
1670 }
1671
1672 /* OI scrub setup/cleanup */
1673
1674 static const char osd_scrub_name[] = "OI_scrub";
1675
1676 int osd_scrub_setup(const struct lu_env *env, struct osd_device *dev)
1677 {
1678         struct osd_thread_info     *info   = osd_oti_get(env);
1679         struct osd_scrub           *scrub  = &dev->od_scrub;
1680         struct lvfs_run_ctxt       *ctxt   = &scrub->os_ctxt;
1681         struct scrub_file          *sf     = &scrub->os_file;
1682         struct super_block         *sb     = osd_sb(dev);
1683         struct ldiskfs_super_block *es     = LDISKFS_SB(sb)->s_es;
1684         struct lvfs_run_ctxt        saved;
1685         struct file                *filp;
1686         int                         dirty  = 0;
1687         int                         rc     = 0;
1688         ENTRY;
1689
1690         memset(scrub, 0, sizeof(*scrub));
1691         OBD_SET_CTXT_MAGIC(ctxt);
1692         ctxt->pwdmnt = dev->od_mnt;
1693         ctxt->pwd = dev->od_mnt->mnt_root;
1694         ctxt->fs = get_ds();
1695
1696         cfs_waitq_init(&scrub->os_thread.t_ctl_waitq);
1697         init_rwsem(&scrub->os_rwsem);
1698         spin_lock_init(&scrub->os_lock);
1699         CFS_INIT_LIST_HEAD(&scrub->os_inconsistent_items);
1700
1701         push_ctxt(&saved, ctxt, NULL);
1702         filp = filp_open(osd_scrub_name, O_RDWR | O_CREAT, 0644);
1703         if (IS_ERR(filp))
1704                 RETURN(PTR_ERR(filp));
1705
1706         scrub->os_inode = igrab(filp->f_dentry->d_inode);
1707         filp_close(filp, 0);
1708         pop_ctxt(&saved, ctxt, NULL);
1709         ldiskfs_set_inode_state(scrub->os_inode,
1710                                 LDISKFS_STATE_LUSTRE_NO_OI);
1711
1712         rc = osd_scrub_file_load(scrub);
1713         if (rc == -ENOENT) {
1714                 osd_scrub_file_init(scrub, es->s_uuid);
1715                 dirty = 1;
1716         } else if (rc != 0) {
1717                 RETURN(rc);
1718         } else {
1719                 if (memcmp(sf->sf_uuid, es->s_uuid, 16) != 0) {
1720                         osd_scrub_file_reset(scrub, es->s_uuid,SF_INCONSISTENT);
1721                         dirty = 1;
1722                 } else if (sf->sf_status == SS_SCANNING) {
1723                         sf->sf_status = SS_CRASHED;
1724                         dirty = 1;
1725                 }
1726         }
1727
1728         if (sf->sf_pos_last_checkpoint != 0)
1729                 scrub->os_pos_current = sf->sf_pos_last_checkpoint + 1;
1730         else
1731                 scrub->os_pos_current = LDISKFS_FIRST_INO(sb) + 1;
1732
1733         if (dirty != 0) {
1734                 rc = osd_scrub_file_store(scrub);
1735                 if (rc != 0)
1736                         RETURN(rc);
1737         }
1738
1739         /* Initialize OI files. */
1740         rc = osd_oi_init(info, dev);
1741         if (rc < 0)
1742                 RETURN(rc);
1743
1744         rc = osd_initial_OI_scrub(info, dev);
1745         if (rc == 0) {
1746                 if ((sf->sf_flags & SF_UPGRADE) &&
1747                    !(sf->sf_flags & SF_INCONSISTENT))
1748                         /* The 'od_igif_inoi' will be set after the
1749                          * upgrading completed, needs NOT remount. */
1750                         dev->od_igif_inoi = 0;
1751                 else
1752                         /* The 'od_igif_inoi' will be set under the
1753                          * following cases:
1754                          * 1) new created system, or
1755                          * 2) restored from file-level backup, or
1756                          * 3) the upgrading completed.
1757                          *
1758                          * The 'od_igif_inoi' may be cleared by OI scrub
1759                          * later if found that the system is upgrading. */
1760                         dev->od_igif_inoi = 1;
1761
1762                 if (!dev->od_noscrub &&
1763                     ((sf->sf_status == SS_PAUSED) ||
1764                      (sf->sf_status == SS_CRASHED &&
1765                       sf->sf_flags & (SF_RECREATED | SF_INCONSISTENT |
1766                                       SF_UPGRADE | SF_AUTO)) ||
1767                      (sf->sf_status == SS_INIT &&
1768                       sf->sf_flags & (SF_RECREATED | SF_INCONSISTENT |
1769                                       SF_UPGRADE))))
1770                         rc = osd_scrub_start(dev);
1771         }
1772
1773         RETURN(rc);
1774 }
1775
1776 void osd_scrub_cleanup(const struct lu_env *env, struct osd_device *dev)
1777 {
1778         struct osd_scrub *scrub = &dev->od_scrub;
1779
1780         LASSERT(dev->od_otable_it == NULL);
1781
1782         if (scrub->os_inode != NULL) {
1783                 osd_scrub_stop(dev);
1784                 iput(scrub->os_inode);
1785                 scrub->os_inode = NULL;
1786         }
1787         if (dev->od_oi_table != NULL)
1788                 osd_oi_fini(osd_oti_get(env), dev);
1789 }
1790
1791 /* object table based iteration APIs */
1792
1793 static struct dt_it *osd_otable_it_init(const struct lu_env *env,
1794                                        struct dt_object *dt, __u32 attr,
1795                                        struct lustre_capa *capa)
1796 {
1797         enum dt_otable_it_flags flags = attr >> DT_OTABLE_IT_FLAGS_SHIFT;
1798         enum dt_otable_it_valid valid = attr & ~DT_OTABLE_IT_FLAGS_MASK;
1799         struct osd_device      *dev   = osd_dev(dt->do_lu.lo_dev);
1800         struct osd_scrub       *scrub = &dev->od_scrub;
1801         struct osd_otable_it   *it;
1802         __u32                   start = 0;
1803         int                     rc;
1804         ENTRY;
1805
1806         /* od_otable_mutex: prevent curcurrent init/fini */
1807         mutex_lock(&dev->od_otable_mutex);
1808         if (dev->od_otable_it != NULL)
1809                 GOTO(out, it = ERR_PTR(-EALREADY));
1810
1811         OBD_ALLOC_PTR(it);
1812         if (it == NULL)
1813                 GOTO(out, it = ERR_PTR(-ENOMEM));
1814
1815         dev->od_otable_it = it;
1816         it->ooi_dev = dev;
1817         it->ooi_cache.ooc_consumer_idx = -1;
1818         if (flags & DOIF_OUTUSED)
1819                 it->ooi_used_outside = 1;
1820
1821         if (flags & DOIF_RESET)
1822                 start |= SS_RESET;
1823
1824         if (valid & DOIV_ERROR_HANDLE) {
1825                 if (flags & DOIF_FAILOUT)
1826                         start |= SS_SET_FAILOUT;
1827                 else
1828                         start |= SS_CLEAR_FAILOUT;
1829         }
1830
1831         rc = do_osd_scrub_start(dev, start);
1832         if (rc < 0 && rc != -EALREADY) {
1833                 dev->od_otable_it = NULL;
1834                 OBD_FREE_PTR(it);
1835                 GOTO(out, it = ERR_PTR(rc));
1836         }
1837
1838         it->ooi_cache.ooc_pos_preload = scrub->os_pos_current;
1839
1840         GOTO(out, it);
1841
1842 out:
1843         mutex_unlock(&dev->od_otable_mutex);
1844         return (struct dt_it *)it;
1845 }
1846
1847 static void osd_otable_it_fini(const struct lu_env *env, struct dt_it *di)
1848 {
1849         struct osd_otable_it *it  = (struct osd_otable_it *)di;
1850         struct osd_device    *dev = it->ooi_dev;
1851
1852         /* od_otable_mutex: prevent curcurrent init/fini */
1853         mutex_lock(&dev->od_otable_mutex);
1854         do_osd_scrub_stop(&dev->od_scrub);
1855         LASSERT(dev->od_otable_it == it);
1856
1857         dev->od_otable_it = NULL;
1858         mutex_unlock(&dev->od_otable_mutex);
1859         OBD_FREE_PTR(it);
1860 }
1861
1862 static int osd_otable_it_get(const struct lu_env *env,
1863                              struct dt_it *di, const struct dt_key *key)
1864 {
1865         return 0;
1866 }
1867
1868 static void osd_otable_it_put(const struct lu_env *env, struct dt_it *di)
1869 {
1870 }
1871
1872 static inline int
1873 osd_otable_it_wakeup(struct osd_scrub *scrub, struct osd_otable_it *it)
1874 {
1875         spin_lock(&scrub->os_lock);
1876         if (it->ooi_cache.ooc_pos_preload < scrub->os_pos_current ||
1877             scrub->os_waiting ||
1878             !thread_is_running(&scrub->os_thread))
1879                 it->ooi_waiting = 0;
1880         else
1881                 it->ooi_waiting = 1;
1882         spin_unlock(&scrub->os_lock);
1883
1884         return !it->ooi_waiting;
1885 }
1886
1887 static int osd_otable_it_next(const struct lu_env *env, struct dt_it *di)
1888 {
1889         struct osd_otable_it    *it     = (struct osd_otable_it *)di;
1890         struct osd_device       *dev    = it->ooi_dev;
1891         struct osd_scrub        *scrub  = &dev->od_scrub;
1892         struct osd_otable_cache *ooc    = &it->ooi_cache;
1893         struct ptlrpc_thread    *thread = &scrub->os_thread;
1894         struct l_wait_info       lwi    = { 0 };
1895         int                      rc;
1896         ENTRY;
1897
1898         LASSERT(it->ooi_user_ready);
1899
1900 again:
1901         if (!thread_is_running(thread) && !it->ooi_used_outside)
1902                 RETURN(1);
1903
1904         if (ooc->ooc_cached_items > 0) {
1905                 ooc->ooc_cached_items--;
1906                 ooc->ooc_consumer_idx = (ooc->ooc_consumer_idx + 1) &
1907                                         ~OSD_OTABLE_IT_CACHE_MASK;
1908                 RETURN(0);
1909         }
1910
1911         if (it->ooi_all_cached) {
1912                 l_wait_event(thread->t_ctl_waitq,
1913                              !thread_is_running(thread),
1914                              &lwi);
1915                 RETURN(1);
1916         }
1917
1918         if (scrub->os_waiting && osd_scrub_has_window(scrub, ooc)) {
1919                 spin_lock(&scrub->os_lock);
1920                 scrub->os_waiting = 0;
1921                 cfs_waitq_broadcast(&scrub->os_thread.t_ctl_waitq);
1922                 spin_unlock(&scrub->os_lock);
1923         }
1924
1925         if (it->ooi_cache.ooc_pos_preload >= scrub->os_pos_current)
1926                 l_wait_event(thread->t_ctl_waitq,
1927                              osd_otable_it_wakeup(scrub, it),
1928                              &lwi);
1929
1930         if (!thread_is_running(thread) && !it->ooi_used_outside)
1931                 RETURN(1);
1932
1933         rc = osd_otable_it_preload(env, it);
1934         if (rc >= 0)
1935                 goto again;
1936
1937         RETURN(rc);
1938 }
1939
1940 static struct dt_key *osd_otable_it_key(const struct lu_env *env,
1941                                         const struct dt_it *di)
1942 {
1943         return NULL;
1944 }
1945
1946 static int osd_otable_it_key_size(const struct lu_env *env,
1947                                   const struct dt_it *di)
1948 {
1949         return sizeof(__u64);
1950 }
1951
1952 static int osd_otable_it_rec(const struct lu_env *env, const struct dt_it *di,
1953                              struct dt_rec *rec, __u32 attr)
1954 {
1955         struct osd_otable_it    *it  = (struct osd_otable_it *)di;
1956         struct osd_otable_cache *ooc = &it->ooi_cache;
1957
1958         *(struct lu_fid *)rec = ooc->ooc_cache[ooc->ooc_consumer_idx].oic_fid;
1959
1960         /* Filter out Invald FID already. */
1961         LASSERTF(fid_is_sane((struct lu_fid *)rec),
1962                  "Invalid FID "DFID", p_idx = %d, c_idx = %d\n",
1963                  PFID((struct lu_fid *)rec),
1964                  ooc->ooc_producer_idx, ooc->ooc_consumer_idx);
1965
1966         return 0;
1967 }
1968
1969 static __u64 osd_otable_it_store(const struct lu_env *env,
1970                                  const struct dt_it *di)
1971 {
1972         struct osd_otable_it    *it  = (struct osd_otable_it *)di;
1973         struct osd_otable_cache *ooc = &it->ooi_cache;
1974         __u64                    hash;
1975
1976         if (it->ooi_user_ready && ooc->ooc_consumer_idx != -1)
1977                 hash = ooc->ooc_cache[ooc->ooc_consumer_idx].oic_lid.oii_ino;
1978         else
1979                 hash = ooc->ooc_pos_preload;
1980         return hash;
1981 }
1982
1983 /**
1984  * Set the OSD layer iteration start position as the specified hash.
1985  */
1986 static int osd_otable_it_load(const struct lu_env *env,
1987                               const struct dt_it *di, __u64 hash)
1988 {
1989         struct osd_otable_it    *it    = (struct osd_otable_it *)di;
1990         struct osd_device       *dev   = it->ooi_dev;
1991         struct osd_otable_cache *ooc   = &it->ooi_cache;
1992         struct osd_scrub        *scrub = &dev->od_scrub;
1993         int                      rc;
1994         ENTRY;
1995
1996         /* Forbid to set iteration position after iteration started. */
1997         if (it->ooi_user_ready)
1998                 RETURN(-EPERM);
1999
2000         if (hash > OSD_OTABLE_MAX_HASH)
2001                 hash = OSD_OTABLE_MAX_HASH;
2002
2003         ooc->ooc_pos_preload = hash;
2004         if (ooc->ooc_pos_preload <= LDISKFS_FIRST_INO(osd_sb(dev)))
2005                 ooc->ooc_pos_preload = LDISKFS_FIRST_INO(osd_sb(dev)) + 1;
2006
2007         it->ooi_user_ready = 1;
2008         if (!scrub->os_full_speed)
2009                 cfs_waitq_broadcast(&scrub->os_thread.t_ctl_waitq);
2010
2011         /* Unplug OSD layer iteration by the first next() call. */
2012         rc = osd_otable_it_next(env, (struct dt_it *)it);
2013
2014         RETURN(rc);
2015 }
2016
2017 static int osd_otable_it_key_rec(const struct lu_env *env,
2018                                  const struct dt_it *di, void *key_rec)
2019 {
2020         return 0;
2021 }
2022
2023 const struct dt_index_operations osd_otable_ops = {
2024         .dio_it = {
2025                 .init     = osd_otable_it_init,
2026                 .fini     = osd_otable_it_fini,
2027                 .get      = osd_otable_it_get,
2028                 .put      = osd_otable_it_put,
2029                 .next     = osd_otable_it_next,
2030                 .key      = osd_otable_it_key,
2031                 .key_size = osd_otable_it_key_size,
2032                 .rec      = osd_otable_it_rec,
2033                 .store    = osd_otable_it_store,
2034                 .load     = osd_otable_it_load,
2035                 .key_rec  = osd_otable_it_key_rec,
2036         }
2037 };
2038
2039 /* high priority inconsistent items list APIs */
2040
2041 int osd_oii_insert(struct osd_device *dev, struct osd_idmap_cache *oic,
2042                    int insert)
2043 {
2044         struct osd_inconsistent_item *oii;
2045         struct osd_scrub             *scrub  = &dev->od_scrub;
2046         struct ptlrpc_thread         *thread = &scrub->os_thread;
2047         int                           wakeup = 0;
2048         ENTRY;
2049
2050         OBD_ALLOC_PTR(oii);
2051         if (unlikely(oii == NULL))
2052                 RETURN(-ENOMEM);
2053
2054         CFS_INIT_LIST_HEAD(&oii->oii_list);
2055         oii->oii_cache = *oic;
2056         oii->oii_insert = insert;
2057
2058         spin_lock(&scrub->os_lock);
2059         if (unlikely(!thread_is_running(thread))) {
2060                 spin_unlock(&scrub->os_lock);
2061                 OBD_FREE_PTR(oii);
2062                 RETURN(-EAGAIN);
2063         }
2064
2065         if (cfs_list_empty(&scrub->os_inconsistent_items))
2066                 wakeup = 1;
2067         cfs_list_add_tail(&oii->oii_list, &scrub->os_inconsistent_items);
2068         spin_unlock(&scrub->os_lock);
2069
2070         if (wakeup != 0)
2071                 cfs_waitq_broadcast(&thread->t_ctl_waitq);
2072
2073         RETURN(0);
2074 }
2075
2076 int osd_oii_lookup(struct osd_device *dev, const struct lu_fid *fid,
2077                    struct osd_inode_id *id)
2078 {
2079         struct osd_scrub             *scrub = &dev->od_scrub;
2080         struct osd_inconsistent_item *oii;
2081         ENTRY;
2082
2083         spin_lock(&scrub->os_lock);
2084         cfs_list_for_each_entry(oii, &scrub->os_inconsistent_items, oii_list) {
2085                 if (lu_fid_eq(fid, &oii->oii_cache.oic_fid)) {
2086                         *id = oii->oii_cache.oic_lid;
2087                         spin_unlock(&scrub->os_lock);
2088                         RETURN(0);
2089                 }
2090         }
2091         spin_unlock(&scrub->os_lock);
2092
2093         RETURN(-ENOENT);
2094 }
2095
2096 /* OI scrub dump */
2097
2098 static const char *scrub_status_names[] = {
2099         "init",
2100         "scanning",
2101         "completed",
2102         "failed",
2103         "stopped",
2104         "paused",
2105         "crashed",
2106         NULL
2107 };
2108
2109 static const char *scrub_flags_names[] = {
2110         "recreated",
2111         "inconsistent",
2112         "auto",
2113         "upgrade",
2114         NULL
2115 };
2116
2117 static const char *scrub_param_names[] = {
2118         "failout",
2119         NULL
2120 };
2121
2122 static int scrub_bits_dump(char **buf, int *len, int bits, const char *names[],
2123                            const char *prefix)
2124 {
2125         int save = *len;
2126         int flag;
2127         int rc;
2128         int i;
2129
2130         rc = snprintf(*buf, *len, "%s:%c", prefix, bits != 0 ? ' ' : '\n');
2131         if (rc <= 0)
2132                 return -ENOSPC;
2133
2134         *buf += rc;
2135         *len -= rc;
2136         for (i = 0, flag = 1; bits != 0; i++, flag = 1 << i) {
2137                 if (flag & bits) {
2138                         bits &= ~flag;
2139                         rc = snprintf(*buf, *len, "%s%c", names[i],
2140                                       bits != 0 ? ',' : '\n');
2141                         if (rc <= 0)
2142                                 return -ENOSPC;
2143
2144                         *buf += rc;
2145                         *len -= rc;
2146                 }
2147         }
2148         return save - *len;
2149 }
2150
2151 static int scrub_time_dump(char **buf, int *len, __u64 time, const char *prefix)
2152 {
2153         int rc;
2154
2155         if (time != 0)
2156                 rc = snprintf(*buf, *len, "%s: "LPU64" seconds\n", prefix,
2157                               cfs_time_current_sec() - time);
2158         else
2159                 rc = snprintf(*buf, *len, "%s: N/A\n", prefix);
2160         if (rc <= 0)
2161                 return -ENOSPC;
2162
2163         *buf += rc;
2164         *len -= rc;
2165         return rc;
2166 }
2167
2168 static int scrub_pos_dump(char **buf, int *len, __u64 pos, const char *prefix)
2169 {
2170         int rc;
2171
2172         if (pos != 0)
2173                 rc = snprintf(*buf, *len, "%s: "LPU64"\n", prefix, pos);
2174         else
2175                 rc = snprintf(*buf, *len, "%s: N/A\n", prefix);
2176         if (rc <= 0)
2177                 return -ENOSPC;
2178
2179         *buf += rc;
2180         *len -= rc;
2181         return rc;
2182 }
2183
2184 int osd_scrub_dump(struct osd_device *dev, char *buf, int len)
2185 {
2186         struct osd_scrub  *scrub   = &dev->od_scrub;
2187         struct scrub_file *sf      = &scrub->os_file;
2188         __u64              checked;
2189         __u64              speed;
2190         int                save    = len;
2191         int                ret     = -ENOSPC;
2192         int                rc;
2193
2194         down_read(&scrub->os_rwsem);
2195         rc = snprintf(buf, len,
2196                       "name: OI_scrub\n"
2197                       "magic: 0x%x\n"
2198                       "oi_files: %d\n"
2199                       "status: %s\n",
2200                       sf->sf_magic, (int)sf->sf_oi_count,
2201                       scrub_status_names[sf->sf_status]);
2202         if (rc <= 0)
2203                 goto out;
2204
2205         buf += rc;
2206         len -= rc;
2207         rc = scrub_bits_dump(&buf, &len, sf->sf_flags, scrub_flags_names,
2208                              "flags");
2209         if (rc < 0)
2210                 goto out;
2211
2212         rc = scrub_bits_dump(&buf, &len, sf->sf_param, scrub_param_names,
2213                              "param");
2214         if (rc < 0)
2215                 goto out;
2216
2217         rc = scrub_time_dump(&buf, &len, sf->sf_time_last_complete,
2218                              "time_since_last_completed");
2219         if (rc < 0)
2220                 goto out;
2221
2222         rc = scrub_time_dump(&buf, &len, sf->sf_time_latest_start,
2223                              "time_since_latest_start");
2224         if (rc < 0)
2225                 goto out;
2226
2227         rc = scrub_time_dump(&buf, &len, sf->sf_time_last_checkpoint,
2228                              "time_since_last_checkpoint");
2229         if (rc < 0)
2230                 goto out;
2231
2232         rc = scrub_pos_dump(&buf, &len, sf->sf_pos_latest_start,
2233                             "latest_start_position");
2234         if (rc < 0)
2235                 goto out;
2236
2237         rc = scrub_pos_dump(&buf, &len, sf->sf_pos_last_checkpoint,
2238                             "last_checkpoint_position");
2239         if (rc < 0)
2240                 goto out;
2241
2242         rc = scrub_pos_dump(&buf, &len, sf->sf_pos_first_inconsistent,
2243                             "first_failure_position");
2244         if (rc < 0)
2245                 goto out;
2246
2247         checked = sf->sf_items_checked + scrub->os_new_checked;
2248         rc = snprintf(buf, len,
2249                       "checked: "LPU64"\n"
2250                       "updated: "LPU64"\n"
2251                       "failed: "LPU64"\n"
2252                       "prior_updated: "LPU64"\n"
2253                       "noscrub: "LPU64"\n"
2254                       "igif: "LPU64"\n"
2255                       "success_count: %u\n",
2256                       checked, sf->sf_items_updated, sf->sf_items_failed,
2257                       sf->sf_items_updated_prior, sf->sf_items_noscrub,
2258                       sf->sf_items_igif, sf->sf_success_count);
2259         if (rc <= 0)
2260                 goto out;
2261
2262         buf += rc;
2263         len -= rc;
2264         speed = checked;
2265         if (thread_is_running(&scrub->os_thread)) {
2266                 cfs_duration_t duration = cfs_time_current() -
2267                                           scrub->os_time_last_checkpoint;
2268                 __u64 new_checked = scrub->os_new_checked * CFS_HZ;
2269                 __u32 rtime = sf->sf_run_time +
2270                               cfs_duration_sec(duration + HALF_SEC);
2271
2272                 if (duration != 0)
2273                         do_div(new_checked, duration);
2274                 if (rtime != 0)
2275                         do_div(speed, rtime);
2276                 rc = snprintf(buf, len,
2277                               "run_time: %u seconds\n"
2278                               "average_speed: "LPU64" objects/sec\n"
2279                               "real-time_speed: "LPU64" objects/sec\n"
2280                               "current_position: %u\n",
2281                               rtime, speed, new_checked, scrub->os_pos_current);
2282         } else {
2283                 if (sf->sf_run_time != 0)
2284                         do_div(speed, sf->sf_run_time);
2285                 rc = snprintf(buf, len,
2286                               "run_time: %u seconds\n"
2287                               "average_speed: "LPU64" objects/sec\n"
2288                               "real-time_speed: N/A\n"
2289                               "current_position: N/A\n",
2290                               sf->sf_run_time, speed);
2291         }
2292         if (rc <= 0)
2293                 goto out;
2294
2295         buf += rc;
2296         len -= rc;
2297         ret = save - len;
2298
2299 out:
2300         up_read(&scrub->os_rwsem);
2301         return ret;
2302 }