Whamcloud - gitweb
LU-9135 osp: do not fail if last_rcvd update failed
[fs/lustre-release.git] / lustre / osp / osp_sync.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2016, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/osp/osp_sync.c
33  *
34  * Lustre OST Proxy Device
35  *
36  * Author: Alex Zhuravlev <alexey.zhuravlev@intel.com>
37  * Author: Mikhail Pershin <mike.pershin@intel.com>
38  */
39
40 #define DEBUG_SUBSYSTEM S_MDS
41
42 #include <linux/kthread.h>
43 #include <lustre_log.h>
44 #include <lustre_update.h>
45 #include "osp_internal.h"
46
47 /*
48  * this is a components of OSP implementing synchronization between MDS and OST
49  * it llogs all interesting changes (currently it's uig/gid change and object
50  * destroy) atomically, then makes sure changes hit OST storage
51  *
52  * we have 4 queues of work:
53  *
54  * the first queue is llog itself, once read a change is stored in 2nd queue
55  * in form of RPC (but RPC isn't fired yet).
56  *
57  * the second queue (opd_sync_waiting_for_commit) holds changes awaiting local
58  * commit. once change is committed locally it migrates onto 3rd queue.
59  *
60  * the third queue (opd_sync_committed_here) holds changes committed locally,
61  * but not sent to OST (as the pipe can be full). once pipe becomes non-full
62  * we take a change from the queue and fire corresponded RPC.
63  *
64  * once RPC is reported committed by OST (using regular last_committed mech.)
65  * the change jumps into 4th queue (opd_sync_committed_there), now we can
66  * cancel corresponded llog record and release RPC
67  *
68  * opd_sync_changes is a number of unread llog records (to be processed).
69  * notice this number doesn't include llog records from previous boots.
70  * with OSP_SYNC_THRESHOLD we try to batch processing a bit (TO BE IMPLEMENTED)
71  *
72  * opd_sync_rpcs_in_progress is total number of requests in above 2-4 queues.
73  * we control this with OSP_MAX_RPCS_IN_PROGRESS so that OSP don't consume
74  * too much memory -- how to deal with 1000th OSTs ? batching could help?
75  *
76  * opd_sync_rpcs_in_flight is a number of RPC in flight.
77  * we control this with OSP_MAX_RPCS_IN_FLIGHT
78  */
79
80 /* XXX: do math to learn reasonable threshold
81  * should it be ~ number of changes fitting bulk? */
82
83 #define OSP_SYNC_THRESHOLD              10
84 #define OSP_MAX_RPCS_IN_FLIGHT          8
85 #define OSP_MAX_RPCS_IN_PROGRESS        4096
86
87 #define OSP_JOB_MAGIC           0x26112005
88
89 struct osp_job_req_args {
90         /** bytes reserved for ptlrpc_replay_req() */
91         struct ptlrpc_replay_async_args jra_raa;
92         struct list_head                jra_committed_link;
93         struct list_head                jra_in_flight_link;
94         struct llog_cookie              jra_lcookie;
95         __u32                           jra_magic;
96 };
97
98 static inline int osp_sync_running(struct osp_device *d)
99 {
100         return !!(d->opd_sync_thread.t_flags & SVC_RUNNING);
101 }
102
103 /**
104  * Check status: whether OSP thread has stopped
105  *
106  * \param[in] d         OSP device
107  *
108  * \retval 0            still running
109  * \retval 1            stopped
110  */
111 static inline int osp_sync_stopped(struct osp_device *d)
112 {
113         return !!(d->opd_sync_thread.t_flags & SVC_STOPPED);
114 }
115
116 /*
117  ** Check for new changes to sync
118  *
119  * \param[in] d         OSP device
120  *
121  * \retval 1            there are changes
122  * \retval 0            there are no changes
123  */
124 static inline int osp_sync_has_new_job(struct osp_device *d)
125 {
126         return atomic_read(&d->opd_sync_changes) > 0 ||
127                 d->opd_sync_prev_done == 0;
128 }
129
130 static inline int osp_sync_in_flight_conflict(struct osp_device *d,
131                                              struct llog_rec_hdr *h)
132 {
133         struct osp_job_req_args *jra;
134         struct ost_id            ostid;
135         int                      conflict = 0;
136
137         if (h == NULL || h->lrh_type == LLOG_GEN_REC ||
138             list_empty(&d->opd_sync_in_flight_list))
139                 return conflict;
140
141         memset(&ostid, 0, sizeof(ostid));
142         switch (h->lrh_type) {
143         case MDS_UNLINK_REC: {
144                 struct llog_unlink_rec *unlink = (struct llog_unlink_rec *)h;
145
146                 ostid_set_seq(&ostid, unlink->lur_oseq);
147                 if (ostid_set_id(&ostid, unlink->lur_oid)) {
148                         CERROR("Bad %llu to set " DOSTID "\n",
149                                (unsigned long long)(unlink->lur_oid),
150                                POSTID(&ostid));
151                         return 1;
152                 }
153                 }
154                 break;
155         case MDS_UNLINK64_REC:
156                 fid_to_ostid(&((struct llog_unlink64_rec *)h)->lur_fid, &ostid);
157                 break;
158         case MDS_SETATTR64_REC:
159                 ostid = ((struct llog_setattr64_rec *)h)->lsr_oi;
160                 break;
161         default:
162                 LBUG();
163         }
164
165         spin_lock(&d->opd_sync_lock);
166         list_for_each_entry(jra, &d->opd_sync_in_flight_list,
167                             jra_in_flight_link) {
168                 struct ptlrpc_request   *req;
169                 struct ost_body         *body;
170
171                 LASSERT(jra->jra_magic == OSP_JOB_MAGIC);
172
173                 req = container_of((void *)jra, struct ptlrpc_request,
174                                    rq_async_args);
175                 body = req_capsule_client_get(&req->rq_pill,
176                                               &RMF_OST_BODY);
177                 LASSERT(body);
178
179                 if (memcmp(&ostid, &body->oa.o_oi, sizeof(ostid)) == 0) {
180                         conflict = 1;
181                         break;
182                 }
183         }
184         spin_unlock(&d->opd_sync_lock);
185
186         return conflict;
187 }
188
189 static inline int osp_sync_rpcs_in_progress_low(struct osp_device *d)
190 {
191         return atomic_read(&d->opd_sync_rpcs_in_progress) <
192                 d->opd_sync_max_rpcs_in_progress;
193 }
194
195 /**
196  * Check for room in the network pipe to OST
197  *
198  * \param[in] d         OSP device
199  *
200  * \retval 1            there is room
201  * \retval 0            no room, the pipe is full
202  */
203 static inline int osp_sync_rpcs_in_flight_low(struct osp_device *d)
204 {
205         return atomic_read(&d->opd_sync_rpcs_in_flight) <
206                 d->opd_sync_max_rpcs_in_flight;
207 }
208
209 /**
210  * Wake up check for the main sync thread
211  *
212  * \param[in] d         OSP device
213  *
214  * \retval 1            time to wake up
215  * \retval 0            no need to wake up
216  */
217 static inline int osp_sync_has_work(struct osp_device *osp)
218 {
219         /* has new/old changes and low in-progress? */
220         if (osp_sync_has_new_job(osp) && osp_sync_rpcs_in_progress_low(osp) &&
221             osp_sync_rpcs_in_flight_low(osp) && osp->opd_imp_connected)
222                 return 1;
223
224         /* has remotely committed? */
225         if (!list_empty(&osp->opd_sync_committed_there))
226                 return 1;
227
228         return 0;
229 }
230
231 void osp_sync_check_for_work(struct osp_device *osp)
232 {
233         if (osp_sync_has_work(osp))
234                 wake_up(&osp->opd_sync_waitq);
235 }
236
237 static inline __u64 osp_sync_correct_id(struct osp_device *d,
238                                         struct llog_rec_hdr *rec)
239 {
240         /*
241          * llog use cyclic store with 32 bit lrh_id
242          * so overflow lrh_id is possible. Range between
243          * last_processed and last_committed is less than
244          * 64745 ^ 2 and less than 2^32 - 1
245          */
246         __u64 correct_id = d->opd_sync_last_committed_id;
247
248         if ((correct_id & 0xffffffffULL) < rec->lrh_id)
249                 correct_id -= 0x100000000ULL;
250
251         correct_id &= ~0xffffffffULL;
252         correct_id |= rec->lrh_id;
253
254         return correct_id;
255 }
256
257 /**
258  * Check and return ready-for-new status.
259  *
260  * The thread processing llog record uses this function to check whether
261  * it's time to take another record and process it. The number of conditions
262  * must be met: the connection should be ready, RPCs in flight not exceeding
263  * the limit, the record is committed locally, etc (see the lines below).
264  *
265  * \param[in] d         OSP device
266  * \param[in] rec       next llog record to process
267  *
268  * \retval 0            not ready
269  * \retval 1            ready
270  */
271 static inline int osp_sync_can_process_new(struct osp_device *d,
272                                            struct llog_rec_hdr *rec)
273 {
274         LASSERT(d);
275
276         if (unlikely(atomic_read(&d->opd_sync_barrier) > 0))
277                 return 0;
278         if (unlikely(osp_sync_in_flight_conflict(d, rec)))
279                 return 0;
280         if (!osp_sync_rpcs_in_progress_low(d))
281                 return 0;
282         if (!osp_sync_rpcs_in_flight_low(d))
283                 return 0;
284         if (!d->opd_imp_connected)
285                 return 0;
286         if (d->opd_sync_prev_done == 0)
287                 return 1;
288         if (atomic_read(&d->opd_sync_changes) == 0)
289                 return 0;
290         if (rec == NULL)
291                 return 1;
292         /* notice "<" not "<=" */
293         if (osp_sync_correct_id(d, rec) < d->opd_sync_last_committed_id)
294                 return 1;
295         return 0;
296 }
297
298 /**
299  * Declare intention to add a new change.
300  *
301  * With regard to OSD API, we have to declare any changes ahead. In this
302  * case we declare an intention to add a llog record representing the
303  * change on the local storage.
304  *
305  * \param[in] env       LU environment provided by the caller
306  * \param[in] o         OSP object
307  * \param[in] type      type of change: MDS_UNLINK64_REC or MDS_SETATTR64_REC
308  * \param[in] th        transaction handle (local)
309  *
310  * \retval 0            on success
311  * \retval negative     negated errno on error
312  */
313 int osp_sync_declare_add(const struct lu_env *env, struct osp_object *o,
314                          llog_op_type type, struct thandle *th)
315 {
316         struct osp_thread_info  *osi = osp_env_info(env);
317         struct osp_device       *d = lu2osp_dev(o->opo_obj.do_lu.lo_dev);
318         struct llog_ctxt        *ctxt;
319         struct thandle          *storage_th;
320         int                      rc;
321
322         ENTRY;
323
324         /* it's a layering violation, to access internals of th,
325          * but we can do this as a sanity check, for a while */
326         LASSERT(th->th_top != NULL);
327         storage_th = thandle_get_sub_by_dt(env, th->th_top, d->opd_storage);
328         if (IS_ERR(storage_th))
329                 RETURN(PTR_ERR(storage_th));
330
331         switch (type) {
332         case MDS_UNLINK64_REC:
333                 osi->osi_hdr.lrh_len = sizeof(struct llog_unlink64_rec);
334                 break;
335         case MDS_SETATTR64_REC:
336                 osi->osi_hdr.lrh_len = sizeof(struct llog_setattr64_rec_v2);
337                 break;
338         default:
339                 LBUG();
340         }
341
342         ctxt = llog_get_context(d->opd_obd, LLOG_MDS_OST_ORIG_CTXT);
343         LASSERT(ctxt);
344
345         rc = llog_declare_add(env, ctxt->loc_handle, &osi->osi_hdr,
346                               storage_th);
347         llog_ctxt_put(ctxt);
348
349         RETURN(rc);
350 }
351
352 /* add the commit callback every second */
353 int osp_sync_add_commit_cb_1s(const struct lu_env *env, struct osp_device *d,
354                               struct thandle *th)
355 {
356         int add = 0;
357
358         /* fast path */
359         if (cfs_time_before(cfs_time_current(), d->opd_sync_next_commit_cb))
360                 return 0;
361
362         spin_lock(&d->opd_sync_lock);
363         if (cfs_time_aftereq(cfs_time_current(), d->opd_sync_next_commit_cb))
364                 add = 1;
365         d->opd_sync_next_commit_cb = cfs_time_shift(1);
366         spin_unlock(&d->opd_sync_lock);
367
368         if (add == 0)
369                 return 0;
370         return osp_sync_add_commit_cb(env, d, th);
371 }
372
373
374 /**
375  * Generate a llog record for a given change.
376  *
377  * Generates a llog record for the change passed. The change can be of two
378  * types: unlink and setattr. The record gets an ID which later will be
379  * used to track commit status of the change. For unlink changes, the caller
380  * can supply a starting FID and the count of the objects to destroy. For
381  * setattr the caller should apply attributes to apply.
382  *
383  *
384  * \param[in] env       LU environment provided by the caller
385  * \param[in] d         OSP device
386  * \param[in] fid       fid of the object the change should be applied to
387  * \param[in] type      type of change: MDS_UNLINK64_REC or MDS_SETATTR64_REC
388  * \param[in] count     count of objects to destroy
389  * \param[in] th        transaction handle (local)
390  * \param[in] attr      attributes for setattr
391  *
392  * \retval 0            on success
393  * \retval negative     negated errno on error
394  */
395 static int osp_sync_add_rec(const struct lu_env *env, struct osp_device *d,
396                             const struct lu_fid *fid, llog_op_type type,
397                             int count, struct thandle *th,
398                             const struct lu_attr *attr)
399 {
400         struct osp_thread_info  *osi = osp_env_info(env);
401         struct llog_ctxt        *ctxt;
402         struct thandle          *storage_th;
403         int                      rc;
404
405         ENTRY;
406
407         /* it's a layering violation, to access internals of th,
408          * but we can do this as a sanity check, for a while */
409         LASSERT(th->th_top != NULL);
410         storage_th = thandle_get_sub_by_dt(env, th->th_top, d->opd_storage);
411         if (IS_ERR(storage_th))
412                 RETURN(PTR_ERR(storage_th));
413
414         switch (type) {
415         case MDS_UNLINK64_REC:
416                 osi->osi_hdr.lrh_len = sizeof(osi->osi_unlink);
417                 osi->osi_hdr.lrh_type = MDS_UNLINK64_REC;
418                 osi->osi_unlink.lur_fid  = *fid;
419                 osi->osi_unlink.lur_count = count;
420                 break;
421         case MDS_SETATTR64_REC:
422                 rc = fid_to_ostid(fid, &osi->osi_oi);
423                 LASSERT(rc == 0);
424                 osi->osi_hdr.lrh_len = sizeof(osi->osi_setattr);
425                 osi->osi_hdr.lrh_type = MDS_SETATTR64_REC;
426                 osi->osi_setattr.lsr_oi  = osi->osi_oi;
427                 LASSERT(attr);
428                 osi->osi_setattr.lsr_uid = attr->la_uid;
429                 osi->osi_setattr.lsr_gid = attr->la_gid;
430                 osi->osi_setattr.lsr_projid = attr->la_projid;
431                 osi->osi_setattr.lsr_valid =
432                         ((attr->la_valid & LA_UID) ? OBD_MD_FLUID : 0) |
433                         ((attr->la_valid & LA_GID) ? OBD_MD_FLGID : 0) |
434                         ((attr->la_valid & LA_PROJID) ? OBD_MD_FLPROJID : 0);
435                 break;
436         default:
437                 LBUG();
438         }
439
440         /* we keep the same id, but increment it when the callback
441          * is registered, so that all records upto the one taken
442          * by the callback are subject to processing */
443         spin_lock(&d->opd_sync_lock);
444         osi->osi_hdr.lrh_id = d->opd_sync_last_used_id;
445         spin_unlock(&d->opd_sync_lock);
446
447         ctxt = llog_get_context(d->opd_obd, LLOG_MDS_OST_ORIG_CTXT);
448         if (ctxt == NULL)
449                 RETURN(-ENOMEM);
450
451         rc = llog_add(env, ctxt->loc_handle, &osi->osi_hdr, &osi->osi_cookie,
452                       storage_th);
453         llog_ctxt_put(ctxt);
454
455         if (likely(rc >= 0)) {
456                 CDEBUG(D_OTHER, "%s: new record "DFID":%x.%u: rc = %d\n",
457                        d->opd_obd->obd_name,
458                        PFID(&osi->osi_cookie.lgc_lgl.lgl_oi.oi_fid),
459                        osi->osi_cookie.lgc_lgl.lgl_ogen,
460                        osi->osi_cookie.lgc_index, rc);
461                 atomic_inc(&d->opd_sync_changes);
462         }
463
464         rc = osp_sync_add_commit_cb_1s(env, d, th);
465
466         /* return 0 always here, error case just cause no llog record */
467         RETURN(0);
468 }
469
470 int osp_sync_add(const struct lu_env *env, struct osp_object *o,
471                  llog_op_type type, struct thandle *th,
472                  const struct lu_attr *attr)
473 {
474         return osp_sync_add_rec(env, lu2osp_dev(o->opo_obj.do_lu.lo_dev),
475                                 lu_object_fid(&o->opo_obj.do_lu), type, 1,
476                                 th, attr);
477 }
478
479 int osp_sync_gap(const struct lu_env *env, struct osp_device *d,
480                         struct lu_fid *fid, int lost, struct thandle *th)
481 {
482         return osp_sync_add_rec(env, d, fid, MDS_UNLINK64_REC, lost, th, NULL);
483 }
484
485 /*
486  * it's quite obvious we can't maintain all the structures in the memory:
487  * while OST is down, MDS can be processing thousands and thousands of unlinks
488  * filling persistent llogs and in-core respresentation
489  *
490  * this doesn't scale at all. so we need basically the following:
491  * a) destroy/setattr append llog records
492  * b) once llog has grown to X records, we process first Y committed records
493  *
494  *  once record R is found via llog_process(), it becomes committed after any
495  *  subsequent commit callback (at the most)
496  */
497
498 /**
499  * ptlrpc commit callback.
500  *
501  * The callback is called by PTLRPC when a RPC is reported committed by the
502  * target (OST). We register the callback for the every RPC applying a change
503  * from the llog. This way we know then the llog records can be cancelled.
504  * Notice the callback can be called when OSP is finishing. We can detect this
505  * checking that actual transno in the request is less or equal of known
506  * committed transno (see osp_sync_process_committed() for the details).
507  * XXX: this is pretty expensive and can be improved later using batching.
508  *
509  * \param[in] req       request
510  */
511 static void osp_sync_request_commit_cb(struct ptlrpc_request *req)
512 {
513         struct osp_device *d = req->rq_cb_data;
514         struct osp_job_req_args *jra;
515
516         CDEBUG(D_HA, "commit req %p, transno %llu\n", req, req->rq_transno);
517
518         if (unlikely(req->rq_transno == 0))
519                 return;
520
521         /* do not do any opd_sync_rpcs_* accounting here
522          * it's done in osp_sync_interpret sooner or later */
523         LASSERT(d);
524
525         jra = ptlrpc_req_async_args(req);
526         LASSERT(jra->jra_magic == OSP_JOB_MAGIC);
527         LASSERT(list_empty(&jra->jra_committed_link));
528
529         ptlrpc_request_addref(req);
530
531         spin_lock(&d->opd_sync_lock);
532         list_add(&jra->jra_committed_link, &d->opd_sync_committed_there);
533         spin_unlock(&d->opd_sync_lock);
534
535         /* XXX: some batching wouldn't hurt */
536         wake_up(&d->opd_sync_waitq);
537 }
538
539 /**
540  * RPC interpretation callback.
541  *
542  * The callback is called by ptlrpc when RPC is replied. Now we have to decide
543  * whether we should:
544  *  - put request on a special list to wait until it's committed by the target,
545  *    if the request is successful
546  *  - schedule llog record cancel if no target object is found
547  *  - try later (essentially after reboot) in case of unexpected error
548  *
549  * \param[in] env       LU environment provided by the caller
550  * \param[in] req       request replied
551  * \param[in] aa        callback data
552  * \param[in] rc        result of RPC
553  *
554  * \retval 0            always
555  */
556 static int osp_sync_interpret(const struct lu_env *env,
557                               struct ptlrpc_request *req, void *aa, int rc)
558 {
559         struct osp_device *d = req->rq_cb_data;
560         struct osp_job_req_args *jra = aa;
561
562         if (jra->jra_magic != OSP_JOB_MAGIC) {
563                 DEBUG_REQ(D_ERROR, req, "bad magic %u\n", jra->jra_magic);
564                 LBUG();
565         }
566         LASSERT(d);
567
568         CDEBUG(D_HA, "reply req %p/%d, rc %d, transno %u\n", req,
569                atomic_read(&req->rq_refcount),
570                rc, (unsigned) req->rq_transno);
571
572         if (rc == -ENOENT) {
573                 /*
574                  * we tried to destroy object or update attributes,
575                  * but object doesn't exist anymore - cancell llog record
576                  */
577                 LASSERT(req->rq_transno == 0);
578                 LASSERT(list_empty(&jra->jra_committed_link));
579
580                 ptlrpc_request_addref(req);
581
582                 spin_lock(&d->opd_sync_lock);
583                 list_add(&jra->jra_committed_link,
584                          &d->opd_sync_committed_there);
585                 spin_unlock(&d->opd_sync_lock);
586
587                 wake_up(&d->opd_sync_waitq);
588         } else if (rc) {
589                 struct obd_import *imp = req->rq_import;
590                 /*
591                  * error happened, we'll try to repeat on next boot ?
592                  */
593                 LASSERTF(req->rq_transno == 0 || rc == -EIO ||
594                          req->rq_import_generation < imp->imp_generation,
595                          "transno %llu, rc %d, gen: req %d, imp %d\n",
596                          req->rq_transno, rc, req->rq_import_generation,
597                          imp->imp_generation);
598                 if (req->rq_transno == 0) {
599                         /* this is the last time we see the request
600                          * if transno is not zero, then commit cb
601                          * will be called at some point */
602                         LASSERT(atomic_read(&d->opd_sync_rpcs_in_progress) > 0);
603                         atomic_dec(&d->opd_sync_rpcs_in_progress);
604                 }
605
606                 wake_up(&d->opd_sync_waitq);
607         } else if (d->opd_pre != NULL &&
608                    unlikely(d->opd_pre_status == -ENOSPC)) {
609                 /*
610                  * if current status is -ENOSPC (lack of free space on OST)
611                  * then we should poll OST immediately once object destroy
612                  * is replied
613                  */
614                 osp_statfs_need_now(d);
615         }
616
617         spin_lock(&d->opd_sync_lock);
618         list_del_init(&jra->jra_in_flight_link);
619         spin_unlock(&d->opd_sync_lock);
620         LASSERT(atomic_read(&d->opd_sync_rpcs_in_flight) > 0);
621         atomic_dec(&d->opd_sync_rpcs_in_flight);
622         if (unlikely(atomic_read(&d->opd_sync_barrier) > 0))
623                 wake_up(&d->opd_sync_barrier_waitq);
624         CDEBUG(D_OTHER, "%s: %d in flight, %d in progress\n",
625                d->opd_obd->obd_name, atomic_read(&d->opd_sync_rpcs_in_flight),
626                atomic_read(&d->opd_sync_rpcs_in_progress));
627
628         osp_sync_check_for_work(d);
629
630         return 0;
631 }
632
633 /*
634  ** Add request to ptlrpc queue.
635  *
636  * This is just a tiny helper function to put the request on the sending list
637  *
638  * \param[in] d         OSP device
639  * \param[in] llh       llog handle where the record is stored
640  * \param[in] h         llog record
641  * \param[in] req       request
642  */
643 static void osp_sync_send_new_rpc(struct osp_device *d,
644                                   struct llog_handle *llh,
645                                   struct llog_rec_hdr *h,
646                                   struct ptlrpc_request *req)
647 {
648         struct osp_job_req_args *jra;
649
650         LASSERT(atomic_read(&d->opd_sync_rpcs_in_flight) <=
651                 d->opd_sync_max_rpcs_in_flight);
652
653         jra = ptlrpc_req_async_args(req);
654         jra->jra_magic = OSP_JOB_MAGIC;
655         jra->jra_lcookie.lgc_lgl = llh->lgh_id;
656         jra->jra_lcookie.lgc_subsys = LLOG_MDS_OST_ORIG_CTXT;
657         jra->jra_lcookie.lgc_index = h->lrh_index;
658         INIT_LIST_HEAD(&jra->jra_committed_link);
659         spin_lock(&d->opd_sync_lock);
660         list_add_tail(&jra->jra_in_flight_link, &d->opd_sync_in_flight_list);
661         spin_unlock(&d->opd_sync_lock);
662
663         ptlrpcd_add_req(req);
664 }
665
666
667 /**
668  * Allocate and prepare RPC for a new change.
669  *
670  * The function allocates and initializes an RPC which will be sent soon to
671  * apply the change to the target OST. The request is initialized from the
672  * llog record passed. Notice only the fields common to all type of changes
673  * are initialized.
674  *
675  * \param[in] d         OSP device
676  * \param[in] op        type of the change
677  * \param[in] format    request format to be used
678  *
679  * \retval pointer              new request on success
680  * \retval ERR_PTR(errno)       on error
681  */
682 static struct ptlrpc_request *osp_sync_new_job(struct osp_device *d,
683                                                ost_cmd_t op,
684                                                const struct req_format *format)
685 {
686         struct ptlrpc_request   *req;
687         struct obd_import       *imp;
688         int                      rc;
689
690         /* Prepare the request */
691         imp = d->opd_obd->u.cli.cl_import;
692         LASSERT(imp);
693
694         if (OBD_FAIL_CHECK(OBD_FAIL_OSP_CHECK_ENOMEM))
695                 RETURN(ERR_PTR(-ENOMEM));
696
697         req = ptlrpc_request_alloc(imp, format);
698         if (req == NULL)
699                 RETURN(ERR_PTR(-ENOMEM));
700
701         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, op);
702         if (rc) {
703                 ptlrpc_req_finished(req);
704                 return ERR_PTR(rc);
705         }
706
707         req->rq_interpret_reply = osp_sync_interpret;
708         req->rq_commit_cb = osp_sync_request_commit_cb;
709         req->rq_cb_data = d;
710
711         ptlrpc_request_set_replen(req);
712
713         return req;
714 }
715
716 /**
717  * Generate a request for setattr change.
718  *
719  * The function prepares a new RPC, initializes it with setattr specific
720  * bits and send the RPC.
721  *
722  * \param[in] d         OSP device
723  * \param[in] llh       llog handle where the record is stored
724  * \param[in] h         llog record
725  *
726  * \retval 0            on success
727  * \retval 1            on invalid record
728  * \retval negative     negated errno on error
729  */
730 static int osp_sync_new_setattr_job(struct osp_device *d,
731                                     struct llog_handle *llh,
732                                     struct llog_rec_hdr *h)
733 {
734         struct llog_setattr64_rec       *rec = (struct llog_setattr64_rec *)h;
735         struct ptlrpc_request           *req;
736         struct ost_body                 *body;
737
738         ENTRY;
739         LASSERT(h->lrh_type == MDS_SETATTR64_REC);
740
741         if (OBD_FAIL_CHECK(OBD_FAIL_OSP_CHECK_INVALID_REC))
742                 RETURN(1);
743
744         /* lsr_valid can only be 0 or HAVE OBD_MD_{FLUID, FLGID, FLPROJID} set,
745          * so no bits other than these should be set. */
746         if ((rec->lsr_valid & ~(OBD_MD_FLUID | OBD_MD_FLGID |
747             OBD_MD_FLPROJID)) != 0) {
748                 CERROR("%s: invalid setattr record, lsr_valid:%llu\n",
749                         d->opd_obd->obd_name, rec->lsr_valid);
750                 /* return 1 on invalid record */
751                 RETURN(1);
752         }
753
754         req = osp_sync_new_job(d, OST_SETATTR, &RQF_OST_SETATTR);
755         if (IS_ERR(req))
756                 RETURN(PTR_ERR(req));
757
758         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
759         LASSERT(body);
760         body->oa.o_oi = rec->lsr_oi;
761         body->oa.o_uid = rec->lsr_uid;
762         body->oa.o_gid = rec->lsr_gid;
763         body->oa.o_valid = OBD_MD_FLGROUP | OBD_MD_FLID;
764         if (h->lrh_len > sizeof(struct llog_setattr64_rec))
765                 body->oa.o_projid = ((struct llog_setattr64_rec_v2 *)
766                                       rec)->lsr_projid;
767
768         /* old setattr record (prior 2.6.0) doesn't have 'valid' stored,
769          * we assume that both UID and GID are valid in that case. */
770         if (rec->lsr_valid == 0)
771                 body->oa.o_valid |= (OBD_MD_FLUID | OBD_MD_FLGID);
772         else
773                 body->oa.o_valid |= rec->lsr_valid;
774
775         osp_sync_send_new_rpc(d, llh, h, req);
776         RETURN(0);
777 }
778
779 /**
780  * Generate a request for unlink change.
781  *
782  * The function prepares a new RPC, initializes it with unlink(destroy)
783  * specific bits and sends the RPC. The function is used to handle
784  * llog_unlink_rec which were used in the older versions of Lustre.
785  * Current version uses llog_unlink_rec64.
786  *
787  * \param[in] d         OSP device
788  * \param[in] llh       llog handle where the record is stored
789  * \param[in] h         llog record
790  *
791  * \retval 0            on success
792  * \retval negative     negated errno on error
793  */
794 static int osp_sync_new_unlink_job(struct osp_device *d,
795                                    struct llog_handle *llh,
796                                    struct llog_rec_hdr *h)
797 {
798         struct llog_unlink_rec  *rec = (struct llog_unlink_rec *)h;
799         struct ptlrpc_request   *req;
800         struct ost_body         *body;
801         int rc;
802
803         ENTRY;
804         LASSERT(h->lrh_type == MDS_UNLINK_REC);
805
806         req = osp_sync_new_job(d, OST_DESTROY, &RQF_OST_DESTROY);
807         if (IS_ERR(req))
808                 RETURN(PTR_ERR(req));
809
810         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
811         LASSERT(body);
812         ostid_set_seq(&body->oa.o_oi, rec->lur_oseq);
813         rc = ostid_set_id(&body->oa.o_oi, rec->lur_oid);
814         if (rc)
815                 return rc;
816         body->oa.o_misc = rec->lur_count;
817         body->oa.o_valid = OBD_MD_FLGROUP | OBD_MD_FLID;
818         if (rec->lur_count)
819                 body->oa.o_valid |= OBD_MD_FLOBJCOUNT;
820
821         osp_sync_send_new_rpc(d, llh, h, req);
822         RETURN(0);
823 }
824
825 /**
826  * Generate a request for unlink change.
827  *
828  * The function prepares a new RPC, initializes it with unlink(destroy)
829  * specific bits and sends the RPC. Depending on the target (MDT or OST)
830  * two different protocols are used. For MDT we use OUT (basically OSD API
831  * updates transferred via a network). For OST we still use the old
832  * protocol (OBD?), originally for compatibility. Later we can start to
833  * use OUT for OST as well, this will allow batching and better code
834  * unification.
835  *
836  * \param[in] d         OSP device
837  * \param[in] llh       llog handle where the record is stored
838  * \param[in] h         llog record
839  *
840  * \retval 0            on success
841  * \retval negative     negated errno on error
842  */
843 static int osp_sync_new_unlink64_job(struct osp_device *d,
844                                      struct llog_handle *llh,
845                                      struct llog_rec_hdr *h)
846 {
847         struct llog_unlink64_rec        *rec = (struct llog_unlink64_rec *)h;
848         struct ptlrpc_request           *req = NULL;
849         struct ost_body                 *body;
850         int                              rc;
851
852         ENTRY;
853         LASSERT(h->lrh_type == MDS_UNLINK64_REC);
854         req = osp_sync_new_job(d, OST_DESTROY, &RQF_OST_DESTROY);
855         if (IS_ERR(req))
856                 RETURN(PTR_ERR(req));
857
858         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
859         if (body == NULL)
860                 RETURN(-EFAULT);
861         rc = fid_to_ostid(&rec->lur_fid, &body->oa.o_oi);
862         if (rc < 0)
863                 RETURN(rc);
864         body->oa.o_misc = rec->lur_count;
865         body->oa.o_valid = OBD_MD_FLGROUP | OBD_MD_FLID |
866                            OBD_MD_FLOBJCOUNT;
867         osp_sync_send_new_rpc(d, llh, h, req);
868         RETURN(0);
869 }
870
871 /**
872  * Process llog records.
873  *
874  * This function is called to process the llog records committed locally.
875  * In the recovery model used by OSP we can apply a change to a remote
876  * target once corresponding transaction (like posix unlink) is committed
877  * locally so can't revert.
878  * Depending on the llog record type, a given handler is called that is
879  * responsible for preparing and sending the RPC to apply the change.
880  * Special record type LLOG_GEN_REC marking a reboot is cancelled right away.
881  *
882  * \param[in] env       LU environment provided by the caller
883  * \param[in] d         OSP device
884  * \param[in] llh       llog handle where the record is stored
885  * \param[in] rec       llog record
886  */
887 static void osp_sync_process_record(const struct lu_env *env,
888                                     struct osp_device *d,
889                                     struct llog_handle *llh,
890                                     struct llog_rec_hdr *rec)
891 {
892         struct llog_handle      *cathandle = llh->u.phd.phd_cat_handle;
893         struct llog_cookie       cookie;
894         int                      rc = 0;
895
896         ENTRY;
897
898         cookie.lgc_lgl = llh->lgh_id;
899         cookie.lgc_subsys = LLOG_MDS_OST_ORIG_CTXT;
900         cookie.lgc_index = rec->lrh_index;
901
902         d->opd_sync_last_catalog_idx = llh->lgh_hdr->llh_cat_idx;
903
904         if (unlikely(rec->lrh_type == LLOG_GEN_REC)) {
905                 struct llog_gen_rec *gen = (struct llog_gen_rec *)rec;
906
907                 /* we're waiting for the record generated by this instance */
908                 LASSERT(d->opd_sync_prev_done == 0);
909                 if (!memcmp(&d->opd_sync_generation, &gen->lgr_gen,
910                             sizeof(gen->lgr_gen))) {
911                         CDEBUG(D_HA, "processed all old entries\n");
912                         d->opd_sync_prev_done = 1;
913                 }
914
915                 /* cancel any generation record */
916                 rc = llog_cat_cancel_records(env, cathandle, 1, &cookie);
917
918                 RETURN_EXIT;
919         }
920
921         /*
922          * now we prepare and fill requests to OST, put them on the queue
923          * and fire after next commit callback
924          */
925
926         /* notice we increment counters before sending RPC, to be consistent
927          * in RPC interpret callback which may happen very quickly */
928         atomic_inc(&d->opd_sync_rpcs_in_flight);
929         atomic_inc(&d->opd_sync_rpcs_in_progress);
930
931         switch (rec->lrh_type) {
932         /* case MDS_UNLINK_REC is kept for compatibility */
933         case MDS_UNLINK_REC:
934                 rc = osp_sync_new_unlink_job(d, llh, rec);
935                 break;
936         case MDS_UNLINK64_REC:
937                 rc = osp_sync_new_unlink64_job(d, llh, rec);
938                 break;
939         case MDS_SETATTR64_REC:
940                 rc = osp_sync_new_setattr_job(d, llh, rec);
941                 break;
942         default:
943                 CERROR("%s: unknown record type: %x\n", d->opd_obd->obd_name,
944                        rec->lrh_type);
945                 /* treat "unknown record type" as "invalid" */
946                 rc = 1;
947                 break;
948         }
949
950         /* For all kinds of records, not matter successful or not,
951          * we should decrease changes and bump last_processed_id.
952          */
953         if (d->opd_sync_prev_done) {
954                 LASSERT(atomic_read(&d->opd_sync_changes) > 0);
955                 atomic_dec(&d->opd_sync_changes);
956                 wake_up(&d->opd_sync_barrier_waitq);
957         }
958         atomic64_inc(&d->opd_sync_processed_recs);
959         if (rc != 0) {
960                 atomic_dec(&d->opd_sync_rpcs_in_flight);
961                 atomic_dec(&d->opd_sync_rpcs_in_progress);
962         }
963
964         CDEBUG(D_OTHER, "%s: %d in flight, %d in progress\n",
965                d->opd_obd->obd_name, atomic_read(&d->opd_sync_rpcs_in_flight),
966                atomic_read(&d->opd_sync_rpcs_in_progress));
967
968         /* Delete the invalid record */
969         if (rc == 1) {
970                 rc = llog_cat_cancel_records(env, cathandle, 1, &cookie);
971                 if (rc != 0)
972                         CERROR("%s: can't delete invalid record: "
973                                "fid = "DFID", rec_id = %u, rc = %d\n",
974                                d->opd_obd->obd_name,
975                                PFID(lu_object_fid(&cathandle->lgh_obj->do_lu)),
976                                rec->lrh_id, rc);
977         }
978
979         CDEBUG(D_HA, "found record %x, %d, idx %u, id %u\n",
980                rec->lrh_type, rec->lrh_len, rec->lrh_index, rec->lrh_id);
981
982         RETURN_EXIT;
983 }
984
985 /**
986  * Cancel llog records for the committed changes.
987  *
988  * The function walks through the list of the committed RPCs and cancels
989  * corresponding llog records. see osp_sync_request_commit_cb() for the
990  * details.
991  *
992  * \param[in] env       LU environment provided by the caller
993  * \param[in] d         OSP device
994  */
995 static void osp_sync_process_committed(const struct lu_env *env,
996                                        struct osp_device *d)
997 {
998         struct obd_device       *obd = d->opd_obd;
999         struct obd_import       *imp = obd->u.cli.cl_import;
1000         struct ost_body         *body;
1001         struct ptlrpc_request   *req;
1002         struct llog_ctxt        *ctxt;
1003         struct llog_handle      *llh;
1004         struct list_head         list;
1005         int                      rc, done = 0;
1006
1007         ENTRY;
1008
1009         if (list_empty(&d->opd_sync_committed_there))
1010                 return;
1011
1012         /*
1013          * if current status is -ENOSPC (lack of free space on OST)
1014          * then we should poll OST immediately once object destroy
1015          * is committed.
1016          * notice: we do this upon commit as well because some backends
1017          * (like DMU) do not release space right away.
1018          */
1019         if (d->opd_pre != NULL && unlikely(d->opd_pre_status == -ENOSPC))
1020                 osp_statfs_need_now(d);
1021
1022         /*
1023          * now cancel them all
1024          * XXX: can we improve this using some batching?
1025          *      with batch RPC that'll happen automatically?
1026          * XXX: can we store ctxt in lod_device and save few cycles ?
1027          */
1028         ctxt = llog_get_context(obd, LLOG_MDS_OST_ORIG_CTXT);
1029         LASSERT(ctxt);
1030
1031         llh = ctxt->loc_handle;
1032         LASSERT(llh);
1033
1034         INIT_LIST_HEAD(&list);
1035         spin_lock(&d->opd_sync_lock);
1036         list_splice(&d->opd_sync_committed_there, &list);
1037         INIT_LIST_HEAD(&d->opd_sync_committed_there);
1038         spin_unlock(&d->opd_sync_lock);
1039
1040         while (!list_empty(&list)) {
1041                 struct osp_job_req_args *jra;
1042
1043                 jra = list_entry(list.next, struct osp_job_req_args,
1044                                  jra_committed_link);
1045                 LASSERT(jra->jra_magic == OSP_JOB_MAGIC);
1046                 list_del_init(&jra->jra_committed_link);
1047
1048                 req = container_of((void *)jra, struct ptlrpc_request,
1049                                    rq_async_args);
1050                 body = req_capsule_client_get(&req->rq_pill,
1051                                               &RMF_OST_BODY);
1052                 LASSERT(body);
1053                 /* import can be closing, thus all commit cb's are
1054                  * called we can check committness directly */
1055                 if (req->rq_import_generation == imp->imp_generation) {
1056                         rc = llog_cat_cancel_records(env, llh, 1,
1057                                                      &jra->jra_lcookie);
1058                         if (rc)
1059                                 CERROR("%s: can't cancel record: %d\n",
1060                                        obd->obd_name, rc);
1061                 } else {
1062                         DEBUG_REQ(D_OTHER, req, "imp_committed = %llu",
1063                                   imp->imp_peer_committed_transno);
1064                 }
1065                 ptlrpc_req_finished(req);
1066                 done++;
1067         }
1068
1069         llog_ctxt_put(ctxt);
1070
1071         LASSERT(atomic_read(&d->opd_sync_rpcs_in_progress) >= done);
1072         atomic_sub(done, &d->opd_sync_rpcs_in_progress);
1073         CDEBUG(D_OTHER, "%s: %d in flight, %d in progress\n",
1074                d->opd_obd->obd_name, atomic_read(&d->opd_sync_rpcs_in_flight),
1075                atomic_read(&d->opd_sync_rpcs_in_progress));
1076
1077         osp_sync_check_for_work(d);
1078
1079         /* wake up the thread if requested to stop:
1080          * it might be waiting for in-progress to complete */
1081         if (unlikely(osp_sync_running(d) == 0))
1082                 wake_up(&d->opd_sync_waitq);
1083
1084         EXIT;
1085 }
1086
1087 /**
1088  * The core of the syncing mechanism.
1089  *
1090  * This is a callback called by the llog processing function. Essentially it
1091  * suspends llog processing until there is a record to process (it's supposed
1092  * to be committed locally). The function handles RPCs committed by the target
1093  * and cancels corresponding llog records.
1094  *
1095  * \param[in] env       LU environment provided by the caller
1096  * \param[in] llh       llog handle we're processing
1097  * \param[in] rec       current llog record
1098  * \param[in] data      callback data containing a pointer to the device
1099  *
1100  * \retval 0                    to ask the caller (llog_process()) to continue
1101  * \retval LLOG_PROC_BREAK      to ask the caller to break
1102  */
1103 static int osp_sync_process_queues(const struct lu_env *env,
1104                                    struct llog_handle *llh,
1105                                    struct llog_rec_hdr *rec,
1106                                    void *data)
1107 {
1108         struct osp_device       *d = data;
1109
1110         do {
1111                 struct l_wait_info lwi = { 0 };
1112
1113                 if (!osp_sync_running(d)) {
1114                         CDEBUG(D_HA, "stop llog processing\n");
1115                         return LLOG_PROC_BREAK;
1116                 }
1117
1118                 /* process requests committed by OST */
1119                 osp_sync_process_committed(env, d);
1120
1121                 /* if we there are changes to be processed and we have
1122                  * resources for this ... do now */
1123                 if (osp_sync_can_process_new(d, rec)) {
1124                         if (llh == NULL) {
1125                                 /* ask llog for another record */
1126                                 CDEBUG(D_HA, "%u changes, %u in progress,"
1127                                      " %u in flight\n",
1128                                      atomic_read(&d->opd_sync_changes),
1129                                      atomic_read(&d->opd_sync_rpcs_in_progress),
1130                                      atomic_read(&d->opd_sync_rpcs_in_flight));
1131                                 return 0;
1132                         }
1133                         osp_sync_process_record(env, d, llh, rec);
1134                         llh = NULL;
1135                         rec = NULL;
1136                 }
1137
1138                 l_wait_event(d->opd_sync_waitq,
1139                              !osp_sync_running(d) ||
1140                              osp_sync_can_process_new(d, rec) ||
1141                              !list_empty(&d->opd_sync_committed_there),
1142                              &lwi);
1143         } while (1);
1144 }
1145
1146 /**
1147  * OSP sync thread.
1148  *
1149  * This thread runs llog_cat_process() scanner calling our callback
1150  * to process llog records. in the callback we implement tricky
1151  * state machine as we don't want to start scanning of the llog again
1152  * and again, also we don't want to process too many records and send
1153  * too many RPCs a time. so, depending on current load (num of changes
1154  * being synced to OST) the callback can suspend awaiting for some
1155  * new conditions, like syncs completed.
1156  *
1157  * In order to process llog records left by previous boots and to allow
1158  * llog_process_thread() to find something (otherwise it'd just exit
1159  * immediately) we add a special GENERATATION record on each boot.
1160  *
1161  * \param[in] _arg      a pointer to thread's arguments
1162  *
1163  * \retval 0            on success
1164  * \retval negative     negated errno on error
1165  */
1166 static int osp_sync_thread(void *_arg)
1167 {
1168         struct osp_device       *d = _arg;
1169         struct ptlrpc_thread    *thread = &d->opd_sync_thread;
1170         struct l_wait_info       lwi = { 0 };
1171         struct llog_ctxt        *ctxt;
1172         struct obd_device       *obd = d->opd_obd;
1173         struct llog_handle      *llh;
1174         struct lu_env            env;
1175         int                      rc, count;
1176         bool                     wrapped;
1177
1178         ENTRY;
1179
1180         rc = lu_env_init(&env, LCT_LOCAL);
1181         if (rc) {
1182                 CERROR("%s: can't initialize env: rc = %d\n",
1183                        obd->obd_name, rc);
1184
1185                 spin_lock(&d->opd_sync_lock);
1186                 thread->t_flags = SVC_STOPPED;
1187                 spin_unlock(&d->opd_sync_lock);
1188                 wake_up(&thread->t_ctl_waitq);
1189
1190                 RETURN(rc);
1191         }
1192
1193         spin_lock(&d->opd_sync_lock);
1194         thread->t_flags = SVC_RUNNING;
1195         spin_unlock(&d->opd_sync_lock);
1196         wake_up(&thread->t_ctl_waitq);
1197
1198         ctxt = llog_get_context(obd, LLOG_MDS_OST_ORIG_CTXT);
1199         if (ctxt == NULL) {
1200                 CERROR("can't get appropriate context\n");
1201                 GOTO(out, rc = -EINVAL);
1202         }
1203
1204         llh = ctxt->loc_handle;
1205         if (llh == NULL) {
1206                 CERROR("can't get llh\n");
1207                 llog_ctxt_put(ctxt);
1208                 GOTO(out, rc = -EINVAL);
1209         }
1210
1211         /*
1212          * Catalog processing stops when it processed last catalog record
1213          * with index equal to the end of catalog bitmap. Or if it is wrapped,
1214          * processing stops with index equal to the lgh_last_idx. We need to
1215          * continue processing.
1216          */
1217         d->opd_sync_last_catalog_idx = 0;
1218         do {
1219                 int     size;
1220
1221                 wrapped = (llh->lgh_hdr->llh_cat_idx >= llh->lgh_last_idx &&
1222                            llh->lgh_hdr->llh_count > 1);
1223
1224                 rc = llog_cat_process(&env, llh, osp_sync_process_queues, d,
1225                                       d->opd_sync_last_catalog_idx, 0);
1226
1227                 size = OBD_FAIL_PRECHECK(OBD_FAIL_CAT_RECORDS) ?
1228                        cfs_fail_val : (LLOG_HDR_BITMAP_SIZE(llh->lgh_hdr) - 1);
1229                 /* processing reaches catalog bottom */
1230                 if (d->opd_sync_last_catalog_idx == size)
1231                         d->opd_sync_last_catalog_idx = 0;
1232                 else if (wrapped)
1233                         /* If catalog is wrapped we can`t predict last index of
1234                          * processing because lgh_last_idx could be changed.
1235                          * Starting form the next one */
1236                         d->opd_sync_last_catalog_idx++;
1237
1238         } while (rc == 0 && (wrapped || d->opd_sync_last_catalog_idx == 0));
1239
1240         if (rc < 0) {
1241                 CERROR("%s: llog process with osp_sync_process_queues "
1242                        "failed: %d\n", d->opd_obd->obd_name, rc);
1243                 GOTO(close, rc);
1244         }
1245         LASSERTF(rc == 0 || rc == LLOG_PROC_BREAK,
1246                  "%u changes, %u in progress, %u in flight: %d\n",
1247                  atomic_read(&d->opd_sync_changes),
1248                  atomic_read(&d->opd_sync_rpcs_in_progress),
1249                  atomic_read(&d->opd_sync_rpcs_in_flight), rc);
1250
1251         /* we don't expect llog_process_thread() to exit till umount */
1252         LASSERTF(thread->t_flags != SVC_RUNNING,
1253                  "%u changes, %u in progress, %u in flight\n",
1254                  atomic_read(&d->opd_sync_changes),
1255                  atomic_read(&d->opd_sync_rpcs_in_progress),
1256                  atomic_read(&d->opd_sync_rpcs_in_flight));
1257
1258         /* wait till all the requests are completed */
1259         count = 0;
1260         while (atomic_read(&d->opd_sync_rpcs_in_progress) > 0) {
1261                 osp_sync_process_committed(&env, d);
1262
1263                 lwi = LWI_TIMEOUT(cfs_time_seconds(5), NULL, NULL);
1264                 rc = l_wait_event(d->opd_sync_waitq,
1265                                 atomic_read(&d->opd_sync_rpcs_in_progress) == 0,
1266                                   &lwi);
1267                 if (rc == -ETIMEDOUT)
1268                         count++;
1269                 LASSERTF(count < 10, "%s: %d %d %sempty\n",
1270                          d->opd_obd->obd_name,
1271                          atomic_read(&d->opd_sync_rpcs_in_progress),
1272                          atomic_read(&d->opd_sync_rpcs_in_flight),
1273                          list_empty(&d->opd_sync_committed_there) ? "" : "!");
1274
1275         }
1276
1277 close:
1278         llog_cat_close(&env, llh);
1279         rc = llog_cleanup(&env, ctxt);
1280         if (rc)
1281                 CERROR("can't cleanup llog: %d\n", rc);
1282 out:
1283         LASSERTF(atomic_read(&d->opd_sync_rpcs_in_progress) == 0,
1284                  "%s: %d %d %sempty\n", d->opd_obd->obd_name,
1285                  atomic_read(&d->opd_sync_rpcs_in_progress),
1286                  atomic_read(&d->opd_sync_rpcs_in_flight),
1287                  list_empty(&d->opd_sync_committed_there) ? "" : "!");
1288
1289         thread->t_flags = SVC_STOPPED;
1290
1291         wake_up(&thread->t_ctl_waitq);
1292
1293         lu_env_fini(&env);
1294
1295         RETURN(0);
1296 }
1297
1298 /**
1299  * Initialize llog.
1300  *
1301  * Initializes the llog. Specific llog to be used depends on the type of the
1302  * target OSP represents (OST or MDT). The function adds appends a new llog
1303  * record to mark the place where the records associated with this boot
1304  * start.
1305  *
1306  * \param[in] env       LU environment provided by the caller
1307  * \param[in] d         OSP device
1308  *
1309  * \retval 0            on success
1310  * \retval negative     negated errno on error
1311  */
1312 static int osp_sync_llog_init(const struct lu_env *env, struct osp_device *d)
1313 {
1314         struct osp_thread_info  *osi = osp_env_info(env);
1315         struct lu_fid           *fid = &osi->osi_fid;
1316         struct llog_handle      *lgh = NULL;
1317         struct obd_device       *obd = d->opd_obd;
1318         struct llog_ctxt        *ctxt;
1319         int                     rc;
1320
1321         ENTRY;
1322
1323         LASSERT(obd);
1324
1325         /*
1326          * open llog corresponding to our OST
1327          */
1328         OBD_SET_CTXT_MAGIC(&obd->obd_lvfs_ctxt);
1329         obd->obd_lvfs_ctxt.dt = d->opd_storage;
1330
1331         lu_local_obj_fid(fid, LLOG_CATALOGS_OID);
1332
1333         rc = llog_osd_get_cat_list(env, d->opd_storage, d->opd_index, 1,
1334                                    &osi->osi_cid, fid);
1335         if (rc < 0) {
1336                 if (rc != -EFAULT) {
1337                         CERROR("%s: can't get id from catalogs: rc = %d\n",
1338                                obd->obd_name, rc);
1339                         RETURN(rc);
1340                 }
1341
1342                 /* After sparse OST indices is supported, the CATALOG file
1343                  * may become a sparse file that results in failure on
1344                  * reading. Skip this error as the llog will be created
1345                  * later */
1346                 memset(&osi->osi_cid, 0, sizeof(osi->osi_cid));
1347                 rc = 0;
1348         }
1349
1350         CDEBUG(D_INFO, "%s: Init llog for %d - catid "DFID":%x\n",
1351                obd->obd_name, d->opd_index,
1352                PFID(&osi->osi_cid.lci_logid.lgl_oi.oi_fid),
1353                osi->osi_cid.lci_logid.lgl_ogen);
1354
1355         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_MDS_OST_ORIG_CTXT,
1356                         d->opd_storage->dd_lu_dev.ld_obd,
1357                         &osp_mds_ost_orig_logops);
1358         if (rc)
1359                 RETURN(rc);
1360
1361         ctxt = llog_get_context(obd, LLOG_MDS_OST_ORIG_CTXT);
1362         LASSERT(ctxt);
1363
1364         if (likely(logid_id(&osi->osi_cid.lci_logid) != 0)) {
1365                 rc = llog_open(env, ctxt, &lgh, &osi->osi_cid.lci_logid, NULL,
1366                                LLOG_OPEN_EXISTS);
1367                 /* re-create llog if it is missing */
1368                 if (rc == -ENOENT)
1369                         logid_set_id(&osi->osi_cid.lci_logid, 0);
1370                 else if (rc < 0)
1371                         GOTO(out_cleanup, rc);
1372         }
1373
1374         if (unlikely(logid_id(&osi->osi_cid.lci_logid) == 0)) {
1375                 rc = llog_open_create(env, ctxt, &lgh, NULL, NULL);
1376                 if (rc < 0)
1377                         GOTO(out_cleanup, rc);
1378                 osi->osi_cid.lci_logid = lgh->lgh_id;
1379         }
1380
1381         LASSERT(lgh != NULL);
1382         ctxt->loc_handle = lgh;
1383
1384         rc = llog_init_handle(env, lgh, LLOG_F_IS_CAT, NULL);
1385         if (rc)
1386                 GOTO(out_close, rc);
1387
1388         rc = llog_osd_put_cat_list(env, d->opd_storage, d->opd_index, 1,
1389                                    &osi->osi_cid, fid);
1390         if (rc)
1391                 GOTO(out_close, rc);
1392
1393         /*
1394          * put a mark in the llog till which we'll be processing
1395          * old records restless
1396          */
1397         d->opd_sync_generation.mnt_cnt = cfs_time_current();
1398         d->opd_sync_generation.conn_cnt = cfs_time_current();
1399
1400         osi->osi_hdr.lrh_type = LLOG_GEN_REC;
1401         osi->osi_hdr.lrh_len = sizeof(osi->osi_gen);
1402
1403         memcpy(&osi->osi_gen.lgr_gen, &d->opd_sync_generation,
1404                sizeof(osi->osi_gen.lgr_gen));
1405
1406         rc = llog_cat_add(env, lgh, &osi->osi_gen.lgr_hdr, &osi->osi_cookie);
1407         if (rc < 0)
1408                 GOTO(out_close, rc);
1409         llog_ctxt_put(ctxt);
1410         RETURN(0);
1411 out_close:
1412         llog_cat_close(env, lgh);
1413 out_cleanup:
1414         llog_cleanup(env, ctxt);
1415         RETURN(rc);
1416 }
1417
1418 /**
1419  * Cleanup llog used for syncing.
1420  *
1421  * Closes and cleanups the llog. The function is called when the device is
1422  * shutting down.
1423  *
1424  * \param[in] env       LU environment provided by the caller
1425  * \param[in] d         OSP device
1426  */
1427 static void osp_sync_llog_fini(const struct lu_env *env, struct osp_device *d)
1428 {
1429         struct llog_ctxt *ctxt;
1430
1431         ctxt = llog_get_context(d->opd_obd, LLOG_MDS_OST_ORIG_CTXT);
1432         if (ctxt) {
1433                 llog_cat_close(env, ctxt->loc_handle);
1434                 llog_cleanup(env, ctxt);
1435         }
1436 }
1437
1438 /**
1439  * Initialization of the sync component of OSP.
1440  *
1441  * Initializes the llog and starts a new thread to handle the changes to
1442  * the remote target (OST or MDT).
1443  *
1444  * \param[in] env       LU environment provided by the caller
1445  * \param[in] d         OSP device
1446  *
1447  * \retval 0            on success
1448  * \retval negative     negated errno on error
1449  */
1450 int osp_sync_init(const struct lu_env *env, struct osp_device *d)
1451 {
1452         struct l_wait_info       lwi = { 0 };
1453         struct task_struct      *task;
1454         int                      rc;
1455
1456         ENTRY;
1457
1458         d->opd_sync_max_rpcs_in_flight = OSP_MAX_RPCS_IN_FLIGHT;
1459         d->opd_sync_max_rpcs_in_progress = OSP_MAX_RPCS_IN_PROGRESS;
1460         spin_lock_init(&d->opd_sync_lock);
1461         init_waitqueue_head(&d->opd_sync_waitq);
1462         init_waitqueue_head(&d->opd_sync_barrier_waitq);
1463         thread_set_flags(&d->opd_sync_thread, SVC_INIT);
1464         init_waitqueue_head(&d->opd_sync_thread.t_ctl_waitq);
1465         INIT_LIST_HEAD(&d->opd_sync_in_flight_list);
1466         INIT_LIST_HEAD(&d->opd_sync_committed_there);
1467
1468         if (d->opd_storage->dd_rdonly)
1469                 RETURN(0);
1470
1471         /*
1472          * initialize llog storing changes
1473          */
1474         rc = osp_sync_llog_init(env, d);
1475         if (rc) {
1476                 CERROR("%s: can't initialize llog: rc = %d\n",
1477                        d->opd_obd->obd_name, rc);
1478                 GOTO(err_id, rc);
1479         }
1480
1481         /*
1482          * Start synchronization thread
1483          */
1484         task = kthread_run(osp_sync_thread, d, "osp-syn-%u-%u",
1485                            d->opd_index, d->opd_group);
1486         if (IS_ERR(task)) {
1487                 rc = PTR_ERR(task);
1488                 CERROR("%s: cannot start sync thread: rc = %d\n",
1489                        d->opd_obd->obd_name, rc);
1490                 GOTO(err_llog, rc);
1491         }
1492
1493         l_wait_event(d->opd_sync_thread.t_ctl_waitq,
1494                      osp_sync_running(d) || osp_sync_stopped(d), &lwi);
1495
1496         RETURN(0);
1497 err_llog:
1498         osp_sync_llog_fini(env, d);
1499 err_id:
1500         return rc;
1501 }
1502
1503 /**
1504  * Stop the syncing thread.
1505  *
1506  * Asks the syncing thread to stop and wait until it's stopped.
1507  *
1508  * \param[in] d         OSP device
1509  *
1510  * \retval              0
1511  */
1512 int osp_sync_fini(struct osp_device *d)
1513 {
1514         struct ptlrpc_thread *thread = &d->opd_sync_thread;
1515
1516         ENTRY;
1517
1518         if (!thread_is_init(thread) && !thread_is_stopped(thread)) {
1519                 thread->t_flags = SVC_STOPPING;
1520                 wake_up(&d->opd_sync_waitq);
1521                 wait_event(thread->t_ctl_waitq, thread_is_stopped(thread));
1522         }
1523
1524         RETURN(0);
1525 }
1526
1527 struct osp_last_committed_cb {
1528         struct dt_txn_commit_cb  ospc_cb;
1529         struct osp_device       *ospc_dev;
1530         __u64                    ospc_transno;
1531 };
1532
1533 void osp_sync_local_commit_cb(struct lu_env *env, struct thandle *th,
1534                               struct dt_txn_commit_cb *dcb, int err)
1535 {
1536         struct osp_last_committed_cb    *cb;
1537         struct osp_device               *d;
1538
1539         cb = container_of0(dcb, struct osp_last_committed_cb, ospc_cb);
1540         d = cb->ospc_dev;
1541
1542         CDEBUG(D_HA, "%s: %llu committed\n", d->opd_obd->obd_name,
1543                cb->ospc_transno);
1544
1545         spin_lock(&d->opd_sync_lock);
1546         if (cb->ospc_transno > d->opd_sync_last_committed_id)
1547                 d->opd_sync_last_committed_id = cb->ospc_transno;
1548         spin_unlock(&d->opd_sync_lock);
1549
1550         osp_sync_check_for_work(d);
1551         lu_device_put(osp2lu_dev(d));
1552         if (atomic_dec_and_test(&d->opd_commits_registered))
1553                 wake_up(&d->opd_sync_waitq);
1554
1555         OBD_FREE_PTR(cb);
1556 }
1557
1558 int osp_sync_add_commit_cb(const struct lu_env *env, struct osp_device *d,
1559                            struct thandle *th)
1560 {
1561         struct osp_last_committed_cb    *cb;
1562         struct dt_txn_commit_cb         *dcb;
1563         int                              rc = 0;
1564
1565         OBD_ALLOC_PTR(cb);
1566         if (cb == NULL)
1567                 return -ENOMEM;
1568         cb->ospc_dev = d;
1569         dcb = &cb->ospc_cb;
1570         dcb->dcb_func = osp_sync_local_commit_cb;
1571         spin_lock(&d->opd_sync_lock);
1572         cb->ospc_transno = ++d->opd_sync_last_used_id;
1573         spin_unlock(&d->opd_sync_lock);
1574
1575         rc = dt_trans_cb_add(th, dcb);
1576         CDEBUG(D_HA, "%s: add commit cb at %llu, next at %llu, rc = %d\n",
1577                d->opd_obd->obd_name, (unsigned long long) cfs_time_current(),
1578                (unsigned long long) d->opd_sync_next_commit_cb, rc);
1579
1580         if (likely(rc == 0)) {
1581                 lu_device_get(osp2lu_dev(d));
1582                 atomic_inc(&d->opd_commits_registered);
1583         } else
1584                 OBD_FREE_PTR(cb);
1585
1586         return rc;
1587 }
1588
1589 /*
1590  * generate an empty transaction and hook the commit callback in
1591  * then force transaction commit
1592  */
1593 void osp_sync_force(const struct lu_env *env, struct osp_device *d)
1594 {
1595         struct thandle *th;
1596         int rc;
1597
1598         th = dt_trans_create(env, d->opd_storage);
1599         if (IS_ERR(th)) {
1600                 CERROR("%s: can't sync\n", d->opd_obd->obd_name);
1601                 return;
1602         }
1603         rc = dt_trans_start_local(env, d->opd_storage, th);
1604         if (rc == 0) {
1605                 CDEBUG(D_OTHER, "%s: sync forced, %d changes\n",
1606                        d->opd_obd->obd_name,
1607                        atomic_read(&d->opd_sync_changes));
1608                 rc = osp_sync_add_commit_cb(env, d, th);
1609                 dt_trans_stop(env, d->opd_storage, th);
1610         }
1611
1612         dt_commit_async(env, d->opd_storage);
1613 }