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