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