Whamcloud - gitweb
6f65aa9039c22e004d44cdddce0146685d5e7eea
[fs/lustre-release.git] / lustre / mgc / mgc_request.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 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/mgc/mgc_request.c
37  *
38  * Author: Nathan Rutman <nathan@clusterfs.com>
39  */
40
41 #define DEBUG_SUBSYSTEM S_MGC
42 #define D_MGC D_CONFIG /*|D_WARNING*/
43
44 #include <linux/module.h>
45 #include <linux/kthread.h>
46
47 #include <dt_object.h>
48 #include <lprocfs_status.h>
49 #include <lustre_dlm.h>
50 #include <lustre_disk.h>
51 #include <lustre_log.h>
52 #include <lustre_swab.h>
53 #include <obd_class.h>
54
55 #include "mgc_internal.h"
56
57 static int mgc_name2resid(char *name, int len, struct ldlm_res_id *res_id,
58                           int type)
59 {
60         __u64 resname = 0;
61
62         if (len > sizeof(resname)) {
63                 CERROR("name too long: %s\n", name);
64                 return -EINVAL;
65         }
66         if (len <= 0) {
67                 CERROR("missing name: %s\n", name);
68                 return -EINVAL;
69         }
70         memcpy(&resname, name, len);
71
72         /* Always use the same endianness for the resid */
73         memset(res_id, 0, sizeof(*res_id));
74         res_id->name[0] = cpu_to_le64(resname);
75         /* XXX: unfortunately, sptlprc and config llog share one lock */
76         switch(type) {
77         case CONFIG_T_CONFIG:
78         case CONFIG_T_SPTLRPC:
79                 resname = 0;
80                 break;
81         case CONFIG_T_RECOVER:
82         case CONFIG_T_PARAMS:
83                 resname = type;
84                 break;
85         default:
86                 LBUG();
87         }
88         res_id->name[1] = cpu_to_le64(resname);
89         CDEBUG(D_MGC, "log %s to resid "LPX64"/"LPX64" (%.8s)\n", name,
90                res_id->name[0], res_id->name[1], (char *)&res_id->name[0]);
91         return 0;
92 }
93
94 int mgc_fsname2resid(char *fsname, struct ldlm_res_id *res_id, int type)
95 {
96         /* fsname is at most 8 chars long, maybe contain "-".
97          * e.g. "lustre", "SUN-000" */
98         return mgc_name2resid(fsname, strlen(fsname), res_id, type);
99 }
100 EXPORT_SYMBOL(mgc_fsname2resid);
101
102 static int mgc_logname2resid(char *logname, struct ldlm_res_id *res_id,
103                              int type)
104 {
105         char *name_end;
106         int len;
107
108         /* logname consists of "fsname-nodetype".
109          * e.g. "lustre-MDT0001", "SUN-000-client"
110          * there is an exception: llog "params" */
111         name_end = strrchr(logname, '-');
112         if (!name_end)
113                 len = strlen(logname);
114         else
115                 len = name_end - logname;
116         return mgc_name2resid(logname, len, res_id, type);
117 }
118
119 /********************** config llog list **********************/
120 static struct list_head config_llog_list = LIST_HEAD_INIT(config_llog_list);
121 static DEFINE_SPINLOCK(config_list_lock);
122
123 /* Take a reference to a config log */
124 static int config_log_get(struct config_llog_data *cld)
125 {
126         ENTRY;
127         atomic_inc(&cld->cld_refcount);
128         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
129                 atomic_read(&cld->cld_refcount));
130         RETURN(0);
131 }
132
133 /* Drop a reference to a config log.  When no longer referenced,
134    we can free the config log data */
135 static void config_log_put(struct config_llog_data *cld)
136 {
137         ENTRY;
138
139         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
140                 atomic_read(&cld->cld_refcount));
141         LASSERT(atomic_read(&cld->cld_refcount) > 0);
142
143         /* spinlock to make sure no item with 0 refcount in the list */
144         if (atomic_dec_and_lock(&cld->cld_refcount, &config_list_lock)) {
145                 list_del(&cld->cld_list_chain);
146                 spin_unlock(&config_list_lock);
147
148                 CDEBUG(D_MGC, "dropping config log %s\n", cld->cld_logname);
149
150                 if (cld->cld_recover)
151                         config_log_put(cld->cld_recover);
152                 if (cld->cld_sptlrpc)
153                         config_log_put(cld->cld_sptlrpc);
154                 if (cld->cld_params)
155                         config_log_put(cld->cld_params);
156                 if (cld_is_sptlrpc(cld))
157                         sptlrpc_conf_log_stop(cld->cld_logname);
158
159                 class_export_put(cld->cld_mgcexp);
160                 OBD_FREE(cld, sizeof(*cld) + strlen(cld->cld_logname) + 1);
161         }
162
163         EXIT;
164 }
165
166 /* Find a config log by name */
167 static
168 struct config_llog_data *config_log_find(char *logname,
169                                          struct config_llog_instance *cfg)
170 {
171         struct config_llog_data *cld;
172         struct config_llog_data *found = NULL;
173         void *                   instance;
174         ENTRY;
175
176         LASSERT(logname != NULL);
177
178         instance = cfg ? cfg->cfg_instance : NULL;
179         spin_lock(&config_list_lock);
180         list_for_each_entry(cld, &config_llog_list, cld_list_chain) {
181                 /* check if instance equals */
182                 if (instance != cld->cld_cfg.cfg_instance)
183                         continue;
184
185                 /* instance may be NULL, should check name */
186                 if (strcmp(logname, cld->cld_logname) == 0) {
187                         found = cld;
188                         break;
189                 }
190         }
191         if (found) {
192                 atomic_inc(&found->cld_refcount);
193                 LASSERT(found->cld_stopping == 0 || cld_is_sptlrpc(found) == 0);
194         }
195         spin_unlock(&config_list_lock);
196         RETURN(found);
197 }
198
199 static
200 struct config_llog_data *do_config_log_add(struct obd_device *obd,
201                                            char *logname,
202                                            int type,
203                                            struct config_llog_instance *cfg,
204                                            struct super_block *sb)
205 {
206         struct config_llog_data *cld;
207         int                      rc;
208         ENTRY;
209
210         CDEBUG(D_MGC, "do adding config log %s:%p\n", logname,
211                cfg ? cfg->cfg_instance : NULL);
212
213         OBD_ALLOC(cld, sizeof(*cld) + strlen(logname) + 1);
214         if (!cld)
215                 RETURN(ERR_PTR(-ENOMEM));
216
217         strcpy(cld->cld_logname, logname);
218         if (cfg)
219                 cld->cld_cfg = *cfg;
220         else
221                 cld->cld_cfg.cfg_callback = class_config_llog_handler;
222         mutex_init(&cld->cld_lock);
223         cld->cld_cfg.cfg_last_idx = 0;
224         cld->cld_cfg.cfg_flags = 0;
225         cld->cld_cfg.cfg_sb = sb;
226         cld->cld_type = type;
227         atomic_set(&cld->cld_refcount, 1);
228
229         /* Keep the mgc around until we are done */
230         cld->cld_mgcexp = class_export_get(obd->obd_self_export);
231
232         if (cld_is_sptlrpc(cld)) {
233                 sptlrpc_conf_log_start(logname);
234                 cld->cld_cfg.cfg_obdname = obd->obd_name;
235         }
236
237         rc = mgc_logname2resid(logname, &cld->cld_resid, type);
238
239         spin_lock(&config_list_lock);
240         list_add(&cld->cld_list_chain, &config_llog_list);
241         spin_unlock(&config_list_lock);
242
243         if (rc) {
244                 config_log_put(cld);
245                 RETURN(ERR_PTR(rc));
246         }
247
248         if (cld_is_sptlrpc(cld)) {
249                 rc = mgc_process_log(obd, cld);
250                 if (rc && rc != -ENOENT)
251                         CERROR("failed processing sptlrpc log: %d\n", rc);
252         }
253
254         RETURN(cld);
255 }
256
257 static struct config_llog_data *config_recover_log_add(struct obd_device *obd,
258         char *fsname,
259         struct config_llog_instance *cfg,
260         struct super_block *sb)
261 {
262         struct config_llog_instance lcfg = *cfg;
263         struct lustre_sb_info *lsi = s2lsi(sb);
264         struct config_llog_data *cld;
265         char logname[32];
266
267         if (IS_OST(lsi))
268                 return NULL;
269
270         /* for osp-on-ost, see lustre_start_osp() */
271         if (IS_MDT(lsi) && lcfg.cfg_instance)
272                 return NULL;
273
274         /* we have to use different llog for clients and mdts for cmd
275          * where only clients are notified if one of cmd server restarts */
276         LASSERT(strlen(fsname) < sizeof(logname) / 2);
277         strcpy(logname, fsname);
278         if (IS_SERVER(lsi)) { /* mdt */
279                 LASSERT(lcfg.cfg_instance == NULL);
280                 lcfg.cfg_instance = sb;
281                 strcat(logname, "-mdtir");
282         } else {
283                 LASSERT(lcfg.cfg_instance != NULL);
284                 strcat(logname, "-cliir");
285         }
286
287         cld = do_config_log_add(obd, logname, CONFIG_T_RECOVER, &lcfg, sb);
288         return cld;
289 }
290
291 static struct config_llog_data *config_params_log_add(struct obd_device *obd,
292         struct config_llog_instance *cfg, struct super_block *sb)
293 {
294         struct config_llog_instance     lcfg = *cfg;
295         struct config_llog_data         *cld;
296
297         lcfg.cfg_instance = sb;
298
299         cld = do_config_log_add(obd, PARAMS_FILENAME, CONFIG_T_PARAMS,
300                                 &lcfg, sb);
301
302         return cld;
303 }
304
305 /** Add this log to the list of active logs watched by an MGC.
306  * Active means we're watching for updates.
307  * We have one active log per "mount" - client instance or servername.
308  * Each instance may be at a different point in the log.
309  */
310 static int config_log_add(struct obd_device *obd, char *logname,
311                           struct config_llog_instance *cfg,
312                           struct super_block *sb)
313 {
314         struct lustre_sb_info   *lsi = s2lsi(sb);
315         struct config_llog_data *cld;
316         struct config_llog_data *sptlrpc_cld;
317         struct config_llog_data *params_cld;
318         char                    seclogname[32];
319         char                    *ptr;
320         int                     rc;
321         ENTRY;
322
323         CDEBUG(D_MGC, "adding config log %s:%p\n", logname, cfg->cfg_instance);
324
325         /*
326          * for each regular log, the depended sptlrpc log name is
327          * <fsname>-sptlrpc. multiple regular logs may share one sptlrpc log.
328          */
329         ptr = strrchr(logname, '-');
330         if (ptr == NULL || ptr - logname > 8) {
331                 CERROR("logname %s is too long\n", logname);
332                 RETURN(-EINVAL);
333         }
334
335         memcpy(seclogname, logname, ptr - logname);
336         strcpy(seclogname + (ptr - logname), "-sptlrpc");
337
338         sptlrpc_cld = config_log_find(seclogname, NULL);
339         if (sptlrpc_cld == NULL) {
340                 sptlrpc_cld = do_config_log_add(obd, seclogname,
341                                                 CONFIG_T_SPTLRPC, NULL, NULL);
342                 if (IS_ERR(sptlrpc_cld)) {
343                         CERROR("can't create sptlrpc log: %s\n", seclogname);
344                         GOTO(out_err, rc = PTR_ERR(sptlrpc_cld));
345                 }
346         }
347         params_cld = config_params_log_add(obd, cfg, sb);
348         if (IS_ERR(params_cld)) {
349                 rc = PTR_ERR(params_cld);
350                 CERROR("%s: can't create params log: rc = %d\n",
351                        obd->obd_name, rc);
352                 GOTO(out_err1, rc);
353         }
354
355         cld = do_config_log_add(obd, logname, CONFIG_T_CONFIG, cfg, sb);
356         if (IS_ERR(cld)) {
357                 CERROR("can't create log: %s\n", logname);
358                 GOTO(out_err2, rc = PTR_ERR(cld));
359         }
360
361         cld->cld_sptlrpc = sptlrpc_cld;
362         cld->cld_params = params_cld;
363
364         LASSERT(lsi->lsi_lmd);
365         if (!(lsi->lsi_lmd->lmd_flags & LMD_FLG_NOIR)) {
366                 struct config_llog_data *recover_cld;
367                 ptr = strrchr(seclogname, '-');
368                 if (ptr != NULL) {
369                         *ptr = 0;
370                 }
371                 else {
372                         CERROR("%s: sptlrpc log name not correct, %s: "
373                                "rc = %d\n", obd->obd_name, seclogname, -EINVAL);
374                         config_log_put(cld);
375                         RETURN(-EINVAL);
376                 }
377                 recover_cld = config_recover_log_add(obd, seclogname, cfg, sb);
378                 if (IS_ERR(recover_cld))
379                         GOTO(out_err3, rc = PTR_ERR(recover_cld));
380                 cld->cld_recover = recover_cld;
381         }
382
383         RETURN(0);
384
385 out_err3:
386         config_log_put(cld);
387
388 out_err2:
389         config_log_put(params_cld);
390
391 out_err1:
392         config_log_put(sptlrpc_cld);
393
394 out_err:
395         RETURN(rc);
396 }
397
398 DEFINE_MUTEX(llog_process_lock);
399
400 /** Stop watching for updates on this log.
401  */
402 static int config_log_end(char *logname, struct config_llog_instance *cfg)
403 {
404         struct config_llog_data *cld;
405         struct config_llog_data *cld_sptlrpc = NULL;
406         struct config_llog_data *cld_params = NULL;
407         struct config_llog_data *cld_recover = NULL;
408         int rc = 0;
409         ENTRY;
410
411         cld = config_log_find(logname, cfg);
412         if (cld == NULL)
413                 RETURN(-ENOENT);
414
415         mutex_lock(&cld->cld_lock);
416         /*
417          * if cld_stopping is set, it means we didn't start the log thus
418          * not owning the start ref. this can happen after previous umount:
419          * the cld still hanging there waiting for lock cancel, and we
420          * remount again but failed in the middle and call log_end without
421          * calling start_log.
422          */
423         if (unlikely(cld->cld_stopping)) {
424                 mutex_unlock(&cld->cld_lock);
425                 /* drop the ref from the find */
426                 config_log_put(cld);
427                 RETURN(rc);
428         }
429
430         cld->cld_stopping = 1;
431
432         cld_recover = cld->cld_recover;
433         cld->cld_recover = NULL;
434         mutex_unlock(&cld->cld_lock);
435
436         if (cld_recover) {
437                 mutex_lock(&cld_recover->cld_lock);
438                 cld_recover->cld_stopping = 1;
439                 mutex_unlock(&cld_recover->cld_lock);
440                 config_log_put(cld_recover);
441         }
442
443         spin_lock(&config_list_lock);
444         cld_sptlrpc = cld->cld_sptlrpc;
445         cld->cld_sptlrpc = NULL;
446         cld_params = cld->cld_params;
447         cld->cld_params = NULL;
448         spin_unlock(&config_list_lock);
449
450         if (cld_sptlrpc)
451                 config_log_put(cld_sptlrpc);
452
453         if (cld_params) {
454                 mutex_lock(&cld_params->cld_lock);
455                 cld_params->cld_stopping = 1;
456                 mutex_unlock(&cld_params->cld_lock);
457                 config_log_put(cld_params);
458         }
459
460         /* drop the ref from the find */
461         config_log_put(cld);
462         /* drop the start ref */
463         config_log_put(cld);
464
465         CDEBUG(D_MGC, "end config log %s (%d)\n", logname ? logname : "client",
466                rc);
467         RETURN(rc);
468 }
469
470 #ifdef CONFIG_PROC_FS
471 int lprocfs_mgc_rd_ir_state(struct seq_file *m, void *data)
472 {
473         struct obd_device       *obd = data;
474         struct obd_import       *imp;
475         struct obd_connect_data *ocd;
476         struct config_llog_data *cld;
477         ENTRY;
478
479         LASSERT(obd != NULL);
480         LPROCFS_CLIMP_CHECK(obd);
481         imp = obd->u.cli.cl_import;
482         ocd = &imp->imp_connect_data;
483
484         seq_printf(m, "imperative_recovery: %s\n",
485                    OCD_HAS_FLAG(ocd, IMP_RECOV) ? "ENABLED" : "DISABLED");
486         seq_printf(m, "client_state:\n");
487
488         spin_lock(&config_list_lock);
489         list_for_each_entry(cld, &config_llog_list, cld_list_chain) {
490                 if (cld->cld_recover == NULL)
491                         continue;
492                 seq_printf(m,  "    - { client: %s, nidtbl_version: %u }\n",
493                            cld->cld_logname,
494                            cld->cld_recover->cld_cfg.cfg_last_idx);
495         }
496         spin_unlock(&config_list_lock);
497
498         LPROCFS_CLIMP_EXIT(obd);
499         RETURN(0);
500 }
501 #endif
502
503 /* reenqueue any lost locks */
504 #define RQ_RUNNING      0x1
505 #define RQ_NOW          0x2
506 #define RQ_LATER        0x4
507 #define RQ_STOP         0x8
508 #define RQ_PRECLEANUP   0x10
509 static int                    rq_state = 0;
510 static wait_queue_head_t      rq_waitq;
511 static DECLARE_COMPLETION(rq_exit);
512 static DECLARE_COMPLETION(rq_start);
513
514 static void do_requeue(struct config_llog_data *cld)
515 {
516         int rc = 0;
517         ENTRY;
518
519         LASSERT(atomic_read(&cld->cld_refcount) > 0);
520
521         /* Do not run mgc_process_log on a disconnected export or an
522          * export which is being disconnected. Take the client
523          * semaphore to make the check non-racy. */
524         down_read(&cld->cld_mgcexp->exp_obd->u.cli.cl_sem);
525         if (cld->cld_mgcexp->exp_obd->u.cli.cl_conn_count != 0) {
526                 CDEBUG(D_MGC, "updating log %s\n", cld->cld_logname);
527                 rc = mgc_process_log(cld->cld_mgcexp->exp_obd, cld);
528                 if (rc && rc != -ENOENT)
529                         CERROR("failed processing log: %d\n", rc);
530         } else {
531                 CDEBUG(D_MGC, "disconnecting, won't update log %s\n",
532                        cld->cld_logname);
533         }
534         up_read(&cld->cld_mgcexp->exp_obd->u.cli.cl_sem);
535
536         EXIT;
537 }
538
539 /* this timeout represents how many seconds MGC should wait before
540  * requeue config and recover lock to the MGS. We need to randomize this
541  * in order to not flood the MGS.
542  */
543 #define MGC_TIMEOUT_MIN_SECONDS   5
544 #define MGC_TIMEOUT_RAND_CENTISEC 0x1ff /* ~500 */
545
546 static int mgc_requeue_thread(void *data)
547 {
548         int rc = 0;
549         bool first = true;
550         ENTRY;
551
552         CDEBUG(D_MGC, "Starting requeue thread\n");
553
554         /* Keep trying failed locks periodically */
555         spin_lock(&config_list_lock);
556         rq_state |= RQ_RUNNING;
557         while (1) {
558                 struct l_wait_info lwi;
559                 struct config_llog_data *cld, *cld_prev;
560                 int rand = cfs_rand() & MGC_TIMEOUT_RAND_CENTISEC;
561                 int stopped = !!(rq_state & RQ_STOP);
562                 int to;
563
564                 /* Any new or requeued lostlocks will change the state */
565                 rq_state &= ~(RQ_NOW | RQ_LATER);
566                 spin_unlock(&config_list_lock);
567
568                 if (first) {
569                         first = false;
570                         complete(&rq_start);
571                 }
572
573                 /* Always wait a few seconds to allow the server who
574                    caused the lock revocation to finish its setup, plus some
575                    random so everyone doesn't try to reconnect at once. */
576                 to = msecs_to_jiffies(MGC_TIMEOUT_MIN_SECONDS * MSEC_PER_SEC);
577                 /* rand is centi-seconds */
578                 to += msecs_to_jiffies(rand * MSEC_PER_SEC / 100);
579                 lwi = LWI_TIMEOUT(to, NULL, NULL);
580                 l_wait_event(rq_waitq, rq_state & (RQ_STOP | RQ_PRECLEANUP),
581                              &lwi);
582
583                 /*
584                  * iterate & processing through the list. for each cld, process
585                  * its depending sptlrpc cld firstly (if any) and then itself.
586                  *
587                  * it's guaranteed any item in the list must have
588                  * reference > 0; and if cld_lostlock is set, at
589                  * least one reference is taken by the previous enqueue.
590                  */
591                 cld_prev = NULL;
592
593                 spin_lock(&config_list_lock);
594                 rq_state &= ~RQ_PRECLEANUP;
595                 list_for_each_entry(cld, &config_llog_list,
596                                         cld_list_chain) {
597                         if (!cld->cld_lostlock)
598                                 continue;
599
600                         spin_unlock(&config_list_lock);
601
602                         LASSERT(atomic_read(&cld->cld_refcount) > 0);
603
604                         /* Whether we enqueued again or not in mgc_process_log,
605                          * we're done with the ref from the old enqueue */
606                         if (cld_prev)
607                                 config_log_put(cld_prev);
608                         cld_prev = cld;
609
610                         cld->cld_lostlock = 0;
611                         if (likely(!stopped))
612                                 do_requeue(cld);
613
614                         spin_lock(&config_list_lock);
615                 }
616                 spin_unlock(&config_list_lock);
617                 if (cld_prev)
618                         config_log_put(cld_prev);
619
620                 /* break after scanning the list so that we can drop
621                  * refcount to losing lock clds */
622                 if (unlikely(stopped)) {
623                         spin_lock(&config_list_lock);
624                         break;
625                 }
626
627                 /* Wait a bit to see if anyone else needs a requeue */
628                 lwi = (struct l_wait_info) { 0 };
629                 l_wait_event(rq_waitq, rq_state & (RQ_NOW | RQ_STOP),
630                              &lwi);
631                 spin_lock(&config_list_lock);
632         }
633         /* spinlock and while guarantee RQ_NOW and RQ_LATER are not set */
634         rq_state &= ~RQ_RUNNING;
635         spin_unlock(&config_list_lock);
636
637         complete(&rq_exit);
638
639         CDEBUG(D_MGC, "Ending requeue thread\n");
640         RETURN(rc);
641 }
642
643 /* Add a cld to the list to requeue.  Start the requeue thread if needed.
644    We are responsible for dropping the config log reference from here on out. */
645 static void mgc_requeue_add(struct config_llog_data *cld)
646 {
647         ENTRY;
648
649         CDEBUG(D_INFO, "log %s: requeue (r=%d sp=%d st=%x)\n",
650                 cld->cld_logname, atomic_read(&cld->cld_refcount),
651                 cld->cld_stopping, rq_state);
652         LASSERT(atomic_read(&cld->cld_refcount) > 0);
653
654         mutex_lock(&cld->cld_lock);
655         if (cld->cld_stopping || cld->cld_lostlock) {
656                 mutex_unlock(&cld->cld_lock);
657                 RETURN_EXIT;
658         }
659         /* this refcount will be released in mgc_requeue_thread. */
660         config_log_get(cld);
661         cld->cld_lostlock = 1;
662         mutex_unlock(&cld->cld_lock);
663
664         /* Hold lock for rq_state */
665         spin_lock(&config_list_lock);
666         if (rq_state & RQ_STOP) {
667                 spin_unlock(&config_list_lock);
668                 cld->cld_lostlock = 0;
669                 config_log_put(cld);
670         } else {
671                 rq_state |= RQ_NOW;
672                 spin_unlock(&config_list_lock);
673                 wake_up(&rq_waitq);
674         }
675         EXIT;
676 }
677
678 /********************** class fns **********************/
679 static int mgc_local_llog_init(const struct lu_env *env,
680                                struct obd_device *obd,
681                                struct obd_device *disk)
682 {
683         struct llog_ctxt        *ctxt;
684         int                      rc;
685
686         ENTRY;
687
688         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_CONFIG_ORIG_CTXT, disk,
689                         &llog_osd_ops);
690         if (rc)
691                 RETURN(rc);
692
693         ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
694         LASSERT(ctxt);
695         ctxt->loc_dir = obd->u.cli.cl_mgc_configs_dir;
696         llog_ctxt_put(ctxt);
697
698         RETURN(0);
699 }
700
701 static int mgc_local_llog_fini(const struct lu_env *env,
702                                struct obd_device *obd)
703 {
704         struct llog_ctxt *ctxt;
705
706         ENTRY;
707
708         ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
709         llog_cleanup(env, ctxt);
710
711         RETURN(0);
712 }
713
714 static int mgc_fs_setup(const struct lu_env *env, struct obd_device *obd,
715                         struct super_block *sb)
716 {
717         struct lustre_sb_info   *lsi = s2lsi(sb);
718         struct client_obd       *cli = &obd->u.cli;
719         struct lu_fid            rfid, fid;
720         struct dt_object        *root, *dto;
721         int                      rc = 0;
722
723         ENTRY;
724
725         LASSERT(lsi);
726         LASSERT(lsi->lsi_dt_dev);
727
728         /* The mgc fs exclusion mutex. Only one fs can be setup at a time. */
729         mutex_lock(&cli->cl_mgc_mutex);
730
731         /* Setup the configs dir */
732         fid.f_seq = FID_SEQ_LOCAL_NAME;
733         fid.f_oid = 1;
734         fid.f_ver = 0;
735         rc = local_oid_storage_init(env, lsi->lsi_dt_dev, &fid,
736                                     &cli->cl_mgc_los);
737         if (rc)
738                 RETURN(rc);
739
740         rc = dt_root_get(env, lsi->lsi_dt_dev, &rfid);
741         if (rc)
742                 GOTO(out_los, rc);
743
744         root = dt_locate_at(env, lsi->lsi_dt_dev, &rfid,
745                             &cli->cl_mgc_los->los_dev->dd_lu_dev, NULL);
746         if (unlikely(IS_ERR(root)))
747                 GOTO(out_los, rc = PTR_ERR(root));
748
749         dto = local_file_find_or_create(env, cli->cl_mgc_los, root,
750                                         MOUNT_CONFIGS_DIR,
751                                         S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO);
752         lu_object_put_nocache(env, &root->do_lu);
753         if (IS_ERR(dto))
754                 GOTO(out_los, rc = PTR_ERR(dto));
755
756         cli->cl_mgc_configs_dir = dto;
757
758         LASSERT(lsi->lsi_osd_exp->exp_obd->obd_lvfs_ctxt.dt);
759         rc = mgc_local_llog_init(env, obd, lsi->lsi_osd_exp->exp_obd);
760         if (rc)
761                 GOTO(out_llog, rc);
762
763         /* We take an obd ref to insure that we can't get to mgc_cleanup
764          * without calling mgc_fs_cleanup first. */
765         class_incref(obd, "mgc_fs", obd);
766
767         /* We keep the cl_mgc_sem until mgc_fs_cleanup */
768         EXIT;
769 out_llog:
770         if (rc) {
771                 lu_object_put(env, &cli->cl_mgc_configs_dir->do_lu);
772                 cli->cl_mgc_configs_dir = NULL;
773         }
774 out_los:
775         if (rc < 0) {
776                 local_oid_storage_fini(env, cli->cl_mgc_los);
777                 cli->cl_mgc_los = NULL;
778                 mutex_unlock(&cli->cl_mgc_mutex);
779         }
780         return rc;
781 }
782
783 static int mgc_fs_cleanup(const struct lu_env *env, struct obd_device *obd)
784 {
785         struct client_obd       *cli = &obd->u.cli;
786         ENTRY;
787
788         LASSERT(cli->cl_mgc_los != NULL);
789
790         mgc_local_llog_fini(env, obd);
791
792         lu_object_put_nocache(env, &cli->cl_mgc_configs_dir->do_lu);
793         cli->cl_mgc_configs_dir = NULL;
794
795         local_oid_storage_fini(env, cli->cl_mgc_los);
796         cli->cl_mgc_los = NULL;
797
798         class_decref(obd, "mgc_fs", obd);
799         mutex_unlock(&cli->cl_mgc_mutex);
800
801         RETURN(0);
802 }
803
804 static int mgc_llog_init(const struct lu_env *env, struct obd_device *obd)
805 {
806         struct llog_ctxt        *ctxt;
807         int                      rc;
808
809         ENTRY;
810
811         /* setup only remote ctxt, the local disk context is switched per each
812          * filesystem during mgc_fs_setup() */
813         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_CONFIG_REPL_CTXT, obd,
814                         &llog_client_ops);
815         if (rc)
816                 RETURN(rc);
817
818         ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
819         LASSERT(ctxt);
820
821         llog_initiator_connect(ctxt);
822         llog_ctxt_put(ctxt);
823
824         RETURN(0);
825 }
826
827 static int mgc_llog_fini(const struct lu_env *env, struct obd_device *obd)
828 {
829         struct llog_ctxt *ctxt;
830
831         ENTRY;
832
833         ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
834         if (ctxt)
835                 llog_cleanup(env, ctxt);
836
837         RETURN(0);
838 }
839
840
841 static atomic_t mgc_count = ATOMIC_INIT(0);
842 static int mgc_precleanup(struct obd_device *obd)
843 {
844         int     rc = 0;
845         int     temp;
846         ENTRY;
847
848         if (atomic_dec_and_test(&mgc_count)) {
849                 LASSERT(rq_state & RQ_RUNNING);
850                 /* stop requeue thread */
851                 temp = RQ_STOP;
852         } else {
853                 /* wakeup requeue thread to clean our cld */
854                 temp = RQ_NOW | RQ_PRECLEANUP;
855         }
856
857         spin_lock(&config_list_lock);
858         rq_state |= temp;
859         spin_unlock(&config_list_lock);
860         wake_up(&rq_waitq);
861
862         if (temp & RQ_STOP)
863                 wait_for_completion(&rq_exit);
864         obd_cleanup_client_import(obd);
865
866         rc = mgc_llog_fini(NULL, obd);
867         if (rc != 0)
868                 CERROR("failed to cleanup llogging subsystems\n");
869
870         RETURN(rc);
871 }
872
873 static int mgc_cleanup(struct obd_device *obd)
874 {
875         int rc;
876         ENTRY;
877
878         /* COMPAT_146 - old config logs may have added profiles we don't
879            know about */
880         if (obd->obd_type->typ_refcnt <= 1)
881                 /* Only for the last mgc */
882                 class_del_profiles();
883
884         lprocfs_obd_cleanup(obd);
885         ptlrpcd_decref();
886
887         rc = client_obd_cleanup(obd);
888         RETURN(rc);
889 }
890
891 static int mgc_setup(struct obd_device *obd, struct lustre_cfg *lcfg)
892 {
893         struct task_struct      *task;
894         int                      rc;
895         ENTRY;
896
897         rc = ptlrpcd_addref();
898         if (rc < 0)
899                 RETURN(rc);
900
901         rc = client_obd_setup(obd, lcfg);
902         if (rc)
903                 GOTO(err_decref, rc);
904
905         rc = mgc_llog_init(NULL, obd);
906         if (rc) {
907                 CERROR("failed to setup llogging subsystems\n");
908                 GOTO(err_cleanup, rc);
909         }
910
911 #ifdef CONFIG_PROC_FS
912         obd->obd_vars = lprocfs_mgc_obd_vars;
913         lprocfs_obd_setup(obd);
914 #endif
915         sptlrpc_lprocfs_cliobd_attach(obd);
916
917         if (atomic_inc_return(&mgc_count) == 1) {
918                 rq_state = 0;
919                 init_waitqueue_head(&rq_waitq);
920
921                 /* start requeue thread */
922                 task = kthread_run(mgc_requeue_thread, NULL, "ll_cfg_requeue");
923                 if (IS_ERR(task)) {
924                         rc = PTR_ERR(task);
925                         CERROR("%s: cannot start requeue thread: rc = %d; "
926                                "no more log updates\n",
927                                obd->obd_name, rc);
928                         GOTO(err_cleanup, rc);
929                 }
930                 /* rc is the task_struct pointer of mgc_requeue_thread. */
931                 rc = 0;
932                 wait_for_completion(&rq_start);
933         }
934
935         RETURN(rc);
936
937 err_cleanup:
938         client_obd_cleanup(obd);
939 err_decref:
940         ptlrpcd_decref();
941         RETURN(rc);
942 }
943
944 /* based on ll_mdc_blocking_ast */
945 static int mgc_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
946                             void *data, int flag)
947 {
948         struct lustre_handle lockh;
949         struct config_llog_data *cld = (struct config_llog_data *)data;
950         int rc = 0;
951         ENTRY;
952
953         switch (flag) {
954         case LDLM_CB_BLOCKING:
955                 /* mgs wants the lock, give it up... */
956                 LDLM_DEBUG(lock, "MGC blocking CB");
957                 ldlm_lock2handle(lock, &lockh);
958                 rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
959                 break;
960         case LDLM_CB_CANCELING:
961                 /* We've given up the lock, prepare ourselves to update. */
962                 LDLM_DEBUG(lock, "MGC cancel CB");
963
964                 CDEBUG(D_MGC, "Lock res "DLDLMRES" (%.8s)\n",
965                        PLDLMRES(lock->l_resource),
966                        (char *)&lock->l_resource->lr_name.name[0]);
967
968                 if (!cld) {
969                         CDEBUG(D_INFO, "missing data, won't requeue\n");
970                         break;
971                 }
972
973                 /* held at mgc_process_log(). */
974                 LASSERT(atomic_read(&cld->cld_refcount) > 0);
975                 /* Are we done with this log? */
976                 if (cld->cld_stopping) {
977                         CDEBUG(D_MGC, "log %s: stopping, won't requeue\n",
978                                 cld->cld_logname);
979                         config_log_put(cld);
980                         break;
981                 }
982                 /* Make sure not to re-enqueue when the mgc is stopping
983                    (we get called from client_disconnect_export) */
984                 if (lock->l_conn_export == NULL ||
985                     lock->l_conn_export->exp_obd->u.cli.cl_conn_count == 0) {
986                         CDEBUG(D_MGC, "log %.8s: disconnecting, won't requeue\n",
987                                 cld->cld_logname);
988                         config_log_put(cld);
989                         break;
990                 }
991
992                 /* Re-enqueue now */
993                 mgc_requeue_add(cld);
994                 config_log_put(cld);
995                 break;
996         default:
997                 LBUG();
998         }
999
1000         RETURN(rc);
1001 }
1002
1003 /* Not sure where this should go... */
1004 /* This is the timeout value for MGS_CONNECT request plus a ping interval, such
1005  * that we can have a chance to try the secondary MGS if any. */
1006 #define  MGC_ENQUEUE_LIMIT (INITIAL_CONNECT_TIMEOUT + (AT_OFF ? 0 : at_min) \
1007                                 + PING_INTERVAL)
1008 #define  MGC_TARGET_REG_LIMIT 10
1009 #define  MGC_SEND_PARAM_LIMIT 10
1010
1011 /* Send parameter to MGS*/
1012 static int mgc_set_mgs_param(struct obd_export *exp,
1013                              struct mgs_send_param *msp)
1014 {
1015         struct ptlrpc_request *req;
1016         struct mgs_send_param *req_msp, *rep_msp;
1017         int rc;
1018         ENTRY;
1019
1020         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
1021                                         &RQF_MGS_SET_INFO, LUSTRE_MGS_VERSION,
1022                                         MGS_SET_INFO);
1023         if (!req)
1024                 RETURN(-ENOMEM);
1025
1026         req_msp = req_capsule_client_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
1027         if (!req_msp) {
1028                 ptlrpc_req_finished(req);
1029                 RETURN(-ENOMEM);
1030         }
1031
1032         memcpy(req_msp, msp, sizeof(*req_msp));
1033         ptlrpc_request_set_replen(req);
1034
1035         /* Limit how long we will wait for the enqueue to complete */
1036         req->rq_delay_limit = MGC_SEND_PARAM_LIMIT;
1037         rc = ptlrpc_queue_wait(req);
1038         if (!rc) {
1039                 rep_msp = req_capsule_server_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
1040                 memcpy(msp, rep_msp, sizeof(*rep_msp));
1041         }
1042
1043         ptlrpc_req_finished(req);
1044
1045         RETURN(rc);
1046 }
1047
1048 /* Take a config lock so we can get cancel notifications */
1049 static int mgc_enqueue(struct obd_export *exp, enum ldlm_type type,
1050                        union ldlm_policy_data *policy, enum ldlm_mode mode,
1051                        __u64 *flags, void *bl_cb, void *cp_cb, void *gl_cb,
1052                        void *data, __u32 lvb_len, void *lvb_swabber,
1053                        struct lustre_handle *lockh)
1054 {
1055         struct config_llog_data *cld = (struct config_llog_data *)data;
1056         struct ldlm_enqueue_info einfo = {
1057                 .ei_type        = type,
1058                 .ei_mode        = mode,
1059                 .ei_cb_bl       = mgc_blocking_ast,
1060                 .ei_cb_cp       = ldlm_completion_ast,
1061         };
1062         struct ptlrpc_request *req;
1063         int short_limit = cld_is_sptlrpc(cld);
1064         int rc;
1065         ENTRY;
1066
1067         CDEBUG(D_MGC, "Enqueue for %s (res "LPX64")\n", cld->cld_logname,
1068                cld->cld_resid.name[0]);
1069
1070         /* We need a callback for every lockholder, so don't try to
1071            ldlm_lock_match (see rev 1.1.2.11.2.47) */
1072         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
1073                                         &RQF_LDLM_ENQUEUE, LUSTRE_DLM_VERSION,
1074                                         LDLM_ENQUEUE);
1075         if (req == NULL)
1076                 RETURN(-ENOMEM);
1077
1078         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER, 0);
1079         ptlrpc_request_set_replen(req);
1080
1081         /* check if this is server or client */
1082         if (cld->cld_cfg.cfg_sb) {
1083                 struct lustre_sb_info *lsi = s2lsi(cld->cld_cfg.cfg_sb);
1084                 if (lsi && IS_SERVER(lsi))
1085                         short_limit = 1;
1086         }
1087         /* Limit how long we will wait for the enqueue to complete */
1088         req->rq_delay_limit = short_limit ? 5 : MGC_ENQUEUE_LIMIT;
1089         rc = ldlm_cli_enqueue(exp, &req, &einfo, &cld->cld_resid, NULL, flags,
1090                               NULL, 0, LVB_T_NONE, lockh, 0);
1091         /* A failed enqueue should still call the mgc_blocking_ast,
1092            where it will be requeued if needed ("grant failed"). */
1093         ptlrpc_req_finished(req);
1094         RETURN(rc);
1095 }
1096
1097 static int mgc_cancel(struct obd_export *exp, enum ldlm_mode mode,
1098                       struct lustre_handle *lockh)
1099 {
1100         ENTRY;
1101
1102         ldlm_lock_decref(lockh, mode);
1103
1104         RETURN(0);
1105 }
1106
1107 static void mgc_notify_active(struct obd_device *unused)
1108 {
1109         /* wakeup mgc_requeue_thread to requeue mgc lock */
1110         spin_lock(&config_list_lock);
1111         rq_state |= RQ_NOW;
1112         spin_unlock(&config_list_lock);
1113         wake_up(&rq_waitq);
1114
1115         /* TODO: Help the MGS rebuild nidtbl. -jay */
1116 }
1117
1118 /* Send target_reg message to MGS */
1119 static int mgc_target_register(struct obd_export *exp,
1120                                struct mgs_target_info *mti)
1121 {
1122         struct ptlrpc_request  *req;
1123         struct mgs_target_info *req_mti, *rep_mti;
1124         int                     rc;
1125         ENTRY;
1126
1127         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
1128                                         &RQF_MGS_TARGET_REG, LUSTRE_MGS_VERSION,
1129                                         MGS_TARGET_REG);
1130         if (req == NULL)
1131                 RETURN(-ENOMEM);
1132
1133         req_mti = req_capsule_client_get(&req->rq_pill, &RMF_MGS_TARGET_INFO);
1134         if (!req_mti) {
1135                 ptlrpc_req_finished(req);
1136                 RETURN(-ENOMEM);
1137         }
1138
1139         memcpy(req_mti, mti, sizeof(*req_mti));
1140         ptlrpc_request_set_replen(req);
1141         CDEBUG(D_MGC, "register %s\n", mti->mti_svname);
1142         /* Limit how long we will wait for the enqueue to complete */
1143         req->rq_delay_limit = MGC_TARGET_REG_LIMIT;
1144
1145         rc = ptlrpc_queue_wait(req);
1146         if (!rc) {
1147                 rep_mti = req_capsule_server_get(&req->rq_pill,
1148                                                  &RMF_MGS_TARGET_INFO);
1149                 memcpy(mti, rep_mti, sizeof(*rep_mti));
1150                 CDEBUG(D_MGC, "register %s got index = %d\n",
1151                        mti->mti_svname, mti->mti_stripe_index);
1152         }
1153         ptlrpc_req_finished(req);
1154
1155         RETURN(rc);
1156 }
1157
1158 static int mgc_set_info_async(const struct lu_env *env, struct obd_export *exp,
1159                               u32 keylen, void *key,
1160                               u32 vallen, void *val,
1161                               struct ptlrpc_request_set *set)
1162 {
1163         int rc = -EINVAL;
1164         ENTRY;
1165
1166         /* Turn off initial_recov after we try all backup servers once */
1167         if (KEY_IS(KEY_INIT_RECOV_BACKUP)) {
1168                 struct obd_import *imp = class_exp2cliimp(exp);
1169                 int value;
1170                 if (vallen != sizeof(int))
1171                         RETURN(-EINVAL);
1172                 value = *(int *)val;
1173                 CDEBUG(D_MGC, "InitRecov %s %d/d%d:i%d:r%d:or%d:%s\n",
1174                        imp->imp_obd->obd_name, value,
1175                        imp->imp_deactive, imp->imp_invalid,
1176                        imp->imp_replayable, imp->imp_obd->obd_replayable,
1177                        ptlrpc_import_state_name(imp->imp_state));
1178                 /* Resurrect if we previously died */
1179                 if ((imp->imp_state != LUSTRE_IMP_FULL &&
1180                      imp->imp_state != LUSTRE_IMP_NEW) || value > 1)
1181                         ptlrpc_reconnect_import(imp);
1182                 RETURN(0);
1183         }
1184         /* FIXME move this to mgc_process_config */
1185         if (KEY_IS(KEY_REGISTER_TARGET)) {
1186                 struct mgs_target_info *mti;
1187                 if (vallen != sizeof(struct mgs_target_info))
1188                         RETURN(-EINVAL);
1189                 mti = (struct mgs_target_info *)val;
1190                 CDEBUG(D_MGC, "register_target %s %#x\n",
1191                        mti->mti_svname, mti->mti_flags);
1192                 rc =  mgc_target_register(exp, mti);
1193                 RETURN(rc);
1194         }
1195         if (KEY_IS(KEY_SET_FS)) {
1196                 struct super_block *sb = (struct super_block *)val;
1197
1198                 if (vallen != sizeof(struct super_block))
1199                         RETURN(-EINVAL);
1200
1201                 rc = mgc_fs_setup(env, exp->exp_obd, sb);
1202                 RETURN(rc);
1203         }
1204         if (KEY_IS(KEY_CLEAR_FS)) {
1205                 if (vallen != 0)
1206                         RETURN(-EINVAL);
1207                 rc = mgc_fs_cleanup(env, exp->exp_obd);
1208                 RETURN(rc);
1209         }
1210         if (KEY_IS(KEY_SET_INFO)) {
1211                 struct mgs_send_param *msp;
1212
1213                 msp = (struct mgs_send_param *)val;
1214                 rc =  mgc_set_mgs_param(exp, msp);
1215                 RETURN(rc);
1216         }
1217         if (KEY_IS(KEY_MGSSEC)) {
1218                 struct client_obd     *cli = &exp->exp_obd->u.cli;
1219                 struct sptlrpc_flavor  flvr;
1220
1221                 /*
1222                  * empty string means using current flavor, if which haven't
1223                  * been set yet, set it as null.
1224                  *
1225                  * if flavor has been set previously, check the asking flavor
1226                  * must match the existing one.
1227                  */
1228                 if (vallen == 0) {
1229                         if (cli->cl_flvr_mgc.sf_rpc != SPTLRPC_FLVR_INVALID)
1230                                 RETURN(0);
1231                         val = "null";
1232                         vallen = 4;
1233                 }
1234
1235                 rc = sptlrpc_parse_flavor(val, &flvr);
1236                 if (rc) {
1237                         CERROR("invalid sptlrpc flavor %s to MGS\n",
1238                                (char *) val);
1239                         RETURN(rc);
1240                 }
1241
1242                 /*
1243                  * caller already hold a mutex
1244                  */
1245                 if (cli->cl_flvr_mgc.sf_rpc == SPTLRPC_FLVR_INVALID) {
1246                         cli->cl_flvr_mgc = flvr;
1247                 } else if (memcmp(&cli->cl_flvr_mgc, &flvr,
1248                                   sizeof(flvr)) != 0) {
1249                         char    str[20];
1250
1251                         sptlrpc_flavor2name(&cli->cl_flvr_mgc,
1252                                             str, sizeof(str));
1253                         LCONSOLE_ERROR("asking sptlrpc flavor %s to MGS but "
1254                                        "currently %s is in use\n",
1255                                        (char *) val, str);
1256                         rc = -EPERM;
1257                 }
1258                 RETURN(rc);
1259         }
1260
1261         RETURN(rc);
1262 }
1263
1264 static int mgc_get_info(const struct lu_env *env, struct obd_export *exp,
1265                         __u32 keylen, void *key, __u32 *vallen, void *val)
1266 {
1267         int rc = -EINVAL;
1268
1269         if (KEY_IS(KEY_CONN_DATA)) {
1270                 struct obd_import *imp = class_exp2cliimp(exp);
1271                 struct obd_connect_data *data = val;
1272
1273                 if (*vallen == sizeof(*data)) {
1274                         *data = imp->imp_connect_data;
1275                         rc = 0;
1276                 }
1277         }
1278
1279         return rc;
1280 }
1281
1282 static int mgc_import_event(struct obd_device *obd,
1283                             struct obd_import *imp,
1284                             enum obd_import_event event)
1285 {
1286         int rc = 0;
1287
1288         LASSERT(imp->imp_obd == obd);
1289         CDEBUG(D_MGC, "import event %#x\n", event);
1290
1291         switch (event) {
1292         case IMP_EVENT_DISCON:
1293                 /* MGC imports should not wait for recovery */
1294                 if (OCD_HAS_FLAG(&imp->imp_connect_data, IMP_RECOV))
1295                         ptlrpc_pinger_ir_down();
1296                 break;
1297         case IMP_EVENT_INACTIVE:
1298                 break;
1299         case IMP_EVENT_INVALIDATE: {
1300                 struct ldlm_namespace *ns = obd->obd_namespace;
1301                 ldlm_namespace_cleanup(ns, LDLM_FL_LOCAL_ONLY);
1302                 break;
1303         }
1304         case IMP_EVENT_ACTIVE:
1305                 CDEBUG(D_INFO, "%s: Reactivating import\n", obd->obd_name);
1306                 /* Clearing obd_no_recov allows us to continue pinging */
1307                 obd->obd_no_recov = 0;
1308                 mgc_notify_active(obd);
1309                 if (OCD_HAS_FLAG(&imp->imp_connect_data, IMP_RECOV))
1310                         ptlrpc_pinger_ir_up();
1311                 break;
1312         case IMP_EVENT_OCD:
1313                 break;
1314         case IMP_EVENT_DEACTIVATE:
1315         case IMP_EVENT_ACTIVATE:
1316                 break;
1317         default:
1318                 CERROR("Unknown import event %#x\n", event);
1319                 LBUG();
1320         }
1321         RETURN(rc);
1322 }
1323
1324 enum {
1325         CONFIG_READ_NRPAGES_INIT = 1 << (20 - PAGE_CACHE_SHIFT),
1326         CONFIG_READ_NRPAGES      = 4
1327 };
1328
1329 static int mgc_apply_recover_logs(struct obd_device *mgc,
1330                                   struct config_llog_data *cld,
1331                                   __u64 max_version,
1332                                   void *data, int datalen, bool mne_swab)
1333 {
1334         struct config_llog_instance *cfg = &cld->cld_cfg;
1335         struct lustre_sb_info       *lsi = s2lsi(cfg->cfg_sb);
1336         struct mgs_nidtbl_entry *entry;
1337         struct lustre_cfg       *lcfg;
1338         struct lustre_cfg_bufs   bufs;
1339         u64   prev_version = 0;
1340         char *inst;
1341         char *buf;
1342         int   bufsz;
1343         int   pos;
1344         int   rc  = 0;
1345         int   off = 0;
1346         ENTRY;
1347
1348         LASSERT(cfg->cfg_instance != NULL);
1349         LASSERT(cfg->cfg_sb == cfg->cfg_instance);
1350
1351         OBD_ALLOC(inst, PAGE_CACHE_SIZE);
1352         if (inst == NULL)
1353                 RETURN(-ENOMEM);
1354
1355         if (!IS_SERVER(lsi)) {
1356                 pos = snprintf(inst, PAGE_CACHE_SIZE, "%p", cfg->cfg_instance);
1357                 if (pos >= PAGE_CACHE_SIZE) {
1358                         OBD_FREE(inst, PAGE_CACHE_SIZE);
1359                         return -E2BIG;
1360                 }
1361         } else {
1362                 LASSERT(IS_MDT(lsi));
1363                 rc = server_name2svname(lsi->lsi_svname, inst, NULL,
1364                                         PAGE_CACHE_SIZE);
1365                 if (rc) {
1366                         OBD_FREE(inst, PAGE_CACHE_SIZE);
1367                         RETURN(-EINVAL);
1368                 }
1369                 pos = strlen(inst);
1370         }
1371
1372         ++pos;
1373         buf   = inst + pos;
1374         bufsz = PAGE_CACHE_SIZE - pos;
1375
1376         while (datalen > 0) {
1377                 int   entry_len = sizeof(*entry);
1378                 int   is_ost, i;
1379                 struct obd_device *obd;
1380                 char *obdname;
1381                 char *cname;
1382                 char *params;
1383                 char *uuid;
1384
1385                 rc = -EINVAL;
1386                 if (datalen < sizeof(*entry))
1387                         break;
1388
1389                 entry = (typeof(entry))(data + off);
1390
1391                 /* sanity check */
1392                 if (entry->mne_nid_type != 0) /* only support type 0 for ipv4 */
1393                         break;
1394                 if (entry->mne_nid_count == 0) /* at least one nid entry */
1395                         break;
1396                 if (entry->mne_nid_size != sizeof(lnet_nid_t))
1397                         break;
1398
1399                 entry_len += entry->mne_nid_count * entry->mne_nid_size;
1400                 if (datalen < entry_len) /* must have entry_len at least */
1401                         break;
1402
1403                 /* Keep this swab for normal mixed endian handling. LU-1644 */
1404                 if (mne_swab)
1405                         lustre_swab_mgs_nidtbl_entry(entry);
1406                 if (entry->mne_length > PAGE_CACHE_SIZE) {
1407                         CERROR("MNE too large (%u)\n", entry->mne_length);
1408                         break;
1409                 }
1410
1411                 if (entry->mne_length < entry_len)
1412                         break;
1413
1414                 off     += entry->mne_length;
1415                 datalen -= entry->mne_length;
1416                 if (datalen < 0)
1417                         break;
1418
1419                 if (entry->mne_version > max_version) {
1420                         CERROR("entry index(%lld) is over max_index(%lld)\n",
1421                                entry->mne_version, max_version);
1422                         break;
1423                 }
1424
1425                 if (prev_version >= entry->mne_version) {
1426                         CERROR("index unsorted, prev %lld, now %lld\n",
1427                                prev_version, entry->mne_version);
1428                         break;
1429                 }
1430                 prev_version = entry->mne_version;
1431
1432                 /*
1433                  * Write a string with format "nid::instance" to
1434                  * lustre/<osc|mdc>/<target>-<osc|mdc>-<instance>/import.
1435                  */
1436
1437                 is_ost = entry->mne_type == LDD_F_SV_TYPE_OST;
1438                 memset(buf, 0, bufsz);
1439                 obdname = buf;
1440                 pos = 0;
1441
1442                 /* lustre-OST0001-osc-<instance #> */
1443                 strcpy(obdname, cld->cld_logname);
1444                 cname = strrchr(obdname, '-');
1445                 if (cname == NULL) {
1446                         CERROR("mgc %s: invalid logname %s\n",
1447                                mgc->obd_name, obdname);
1448                         break;
1449                 }
1450
1451                 pos = cname - obdname;
1452                 obdname[pos] = 0;
1453                 pos += sprintf(obdname + pos, "-%s%04x",
1454                                   is_ost ? "OST" : "MDT", entry->mne_index);
1455
1456                 cname = is_ost ? "osc" : "mdc",
1457                 pos += sprintf(obdname + pos, "-%s-%s", cname, inst);
1458                 lustre_cfg_bufs_reset(&bufs, obdname);
1459
1460                 /* find the obd by obdname */
1461                 obd = class_name2obd(obdname);
1462                 if (obd == NULL) {
1463                         CDEBUG(D_INFO, "mgc %s: cannot find obdname %s\n",
1464                                mgc->obd_name, obdname);
1465                         rc = 0;
1466                         /* this is a safe race, when the ost is starting up...*/
1467                         continue;
1468                 }
1469
1470                 /* osc.import = "connection=<Conn UUID>::<target instance>" */
1471                 ++pos;
1472                 params = buf + pos;
1473                 pos += sprintf(params, "%s.import=%s", cname, "connection=");
1474                 uuid = buf + pos;
1475
1476                 down_read(&obd->u.cli.cl_sem);
1477                 if (obd->u.cli.cl_import == NULL) {
1478                         /* client does not connect to the OST yet */
1479                         up_read(&obd->u.cli.cl_sem);
1480                         rc = 0;
1481                         continue;
1482                 }
1483
1484                 /* iterate all nids to find one */
1485                 /* find uuid by nid */
1486                 rc = -ENOENT;
1487                 for (i = 0; i < entry->mne_nid_count; i++) {
1488                         rc = client_import_find_conn(obd->u.cli.cl_import,
1489                                                      entry->u.nids[i],
1490                                                      (struct obd_uuid *)uuid);
1491                         if (rc == 0)
1492                                 break;
1493                 }
1494
1495                 up_read(&obd->u.cli.cl_sem);
1496                 if (rc < 0) {
1497                         CERROR("mgc: cannot find uuid by nid %s\n",
1498                                libcfs_nid2str(entry->u.nids[0]));
1499                         break;
1500                 }
1501
1502                 CDEBUG(D_INFO, "Find uuid %s by nid %s\n",
1503                        uuid, libcfs_nid2str(entry->u.nids[0]));
1504
1505                 pos += strlen(uuid);
1506                 pos += sprintf(buf + pos, "::%u", entry->mne_instance);
1507                 LASSERT(pos < bufsz);
1508
1509                 lustre_cfg_bufs_set_string(&bufs, 1, params);
1510
1511                 lcfg = lustre_cfg_new(LCFG_PARAM, &bufs);
1512                 if (lcfg == NULL) {
1513                         rc = -ENOMEM;
1514                         break;
1515                 }
1516
1517                 CDEBUG(D_INFO, "ir apply logs "LPD64"/"LPD64" for %s -> %s\n",
1518                        prev_version, max_version, obdname, params);
1519
1520                 rc = class_process_config(lcfg);
1521                 lustre_cfg_free(lcfg);
1522                 if (rc)
1523                         CDEBUG(D_INFO, "process config for %s error %d\n",
1524                                obdname, rc);
1525
1526                 /* continue, even one with error */
1527         }
1528
1529         OBD_FREE(inst, PAGE_CACHE_SIZE);
1530         RETURN(rc);
1531 }
1532
1533 /**
1534  * This function is called if this client was notified for target restarting
1535  * by the MGS. A CONFIG_READ RPC is going to send to fetch recovery logs.
1536  */
1537 static int mgc_process_recover_log(struct obd_device *obd,
1538                                    struct config_llog_data *cld)
1539 {
1540         struct ptlrpc_request *req = NULL;
1541         struct config_llog_instance *cfg = &cld->cld_cfg;
1542         struct mgs_config_body *body;
1543         struct mgs_config_res  *res;
1544         struct ptlrpc_bulk_desc *desc;
1545         struct page **pages;
1546         int nrpages;
1547         bool eof = true;
1548         bool mne_swab = false;
1549         int i;
1550         int ealen;
1551         int rc;
1552         ENTRY;
1553
1554         /* allocate buffer for bulk transfer.
1555          * if this is the first time for this mgs to read logs,
1556          * CONFIG_READ_NRPAGES_INIT will be used since it will read all logs
1557          * once; otherwise, it only reads increment of logs, this should be
1558          * small and CONFIG_READ_NRPAGES will be used.
1559          */
1560         nrpages = CONFIG_READ_NRPAGES;
1561         if (cfg->cfg_last_idx == 0) /* the first time */
1562                 nrpages = CONFIG_READ_NRPAGES_INIT;
1563
1564         OBD_ALLOC(pages, sizeof(*pages) * nrpages);
1565         if (pages == NULL)
1566                 GOTO(out, rc = -ENOMEM);
1567
1568         for (i = 0; i < nrpages; i++) {
1569                 pages[i] = alloc_page(GFP_KERNEL);
1570                 if (pages[i] == NULL)
1571                         GOTO(out, rc = -ENOMEM);
1572         }
1573
1574 again:
1575         LASSERT(cld_is_recover(cld));
1576         LASSERT(mutex_is_locked(&cld->cld_lock));
1577         req = ptlrpc_request_alloc(class_exp2cliimp(cld->cld_mgcexp),
1578                                    &RQF_MGS_CONFIG_READ);
1579         if (req == NULL)
1580                 GOTO(out, rc = -ENOMEM);
1581
1582         rc = ptlrpc_request_pack(req, LUSTRE_MGS_VERSION, MGS_CONFIG_READ);
1583         if (rc)
1584                 GOTO(out, rc);
1585
1586         /* pack request */
1587         body = req_capsule_client_get(&req->rq_pill, &RMF_MGS_CONFIG_BODY);
1588         LASSERT(body != NULL);
1589         LASSERT(sizeof(body->mcb_name) > strlen(cld->cld_logname));
1590         if (strlcpy(body->mcb_name, cld->cld_logname, sizeof(body->mcb_name))
1591             >= sizeof(body->mcb_name))
1592                 GOTO(out, rc = -E2BIG);
1593         body->mcb_offset = cfg->cfg_last_idx + 1;
1594         body->mcb_type   = cld->cld_type;
1595         body->mcb_bits   = PAGE_CACHE_SHIFT;
1596         body->mcb_units  = nrpages;
1597
1598         /* allocate bulk transfer descriptor */
1599         desc = ptlrpc_prep_bulk_imp(req, nrpages, 1,
1600                                     PTLRPC_BULK_PUT_SINK | PTLRPC_BULK_BUF_KIOV,
1601                                     MGS_BULK_PORTAL,
1602                                     &ptlrpc_bulk_kiov_pin_ops);
1603         if (desc == NULL)
1604                 GOTO(out, rc = -ENOMEM);
1605
1606         for (i = 0; i < nrpages; i++)
1607                 desc->bd_frag_ops->add_kiov_frag(desc, pages[i], 0,
1608                                                  PAGE_CACHE_SIZE);
1609
1610         ptlrpc_request_set_replen(req);
1611         rc = ptlrpc_queue_wait(req);
1612         if (rc)
1613                 GOTO(out, rc);
1614
1615         res = req_capsule_server_get(&req->rq_pill, &RMF_MGS_CONFIG_RES);
1616         if (res->mcr_size < res->mcr_offset)
1617                 GOTO(out, rc = -EINVAL);
1618
1619         /* always update the index even though it might have errors with
1620          * handling the recover logs */
1621         cfg->cfg_last_idx = res->mcr_offset;
1622         eof = res->mcr_offset == res->mcr_size;
1623
1624         CDEBUG(D_INFO, "Latest version "LPD64", more %d.\n",
1625                res->mcr_offset, eof == false);
1626
1627         ealen = sptlrpc_cli_unwrap_bulk_read(req, req->rq_bulk, 0);
1628         if (ealen < 0)
1629                 GOTO(out, rc = ealen);
1630
1631         if (ealen > nrpages << PAGE_CACHE_SHIFT)
1632                 GOTO(out, rc = -EINVAL);
1633
1634         if (ealen == 0) { /* no logs transferred */
1635                 if (!eof)
1636                         rc = -EINVAL;
1637                 GOTO(out, rc);
1638         }
1639
1640         mne_swab = !!ptlrpc_rep_need_swab(req);
1641 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
1642         /* This import flag means the server did an extra swab of IR MNE
1643          * records (fixed in LU-1252), reverse it here if needed. LU-1644 */
1644         if (unlikely(req->rq_import->imp_need_mne_swab))
1645                 mne_swab = !mne_swab;
1646 #endif
1647
1648         for (i = 0; i < nrpages && ealen > 0; i++) {
1649                 int rc2;
1650                 void *ptr;
1651
1652                 ptr = kmap(pages[i]);
1653                 rc2 = mgc_apply_recover_logs(obd, cld, res->mcr_offset, ptr,
1654                                              min_t(int, ealen, PAGE_CACHE_SIZE),
1655                                              mne_swab);
1656                 kunmap(pages[i]);
1657                 if (rc2 < 0) {
1658                         CWARN("Process recover log %s error %d\n",
1659                               cld->cld_logname, rc2);
1660                         break;
1661                 }
1662
1663                 ealen -= PAGE_CACHE_SIZE;
1664         }
1665
1666 out:
1667         if (req)
1668                 ptlrpc_req_finished(req);
1669
1670         if (rc == 0 && !eof)
1671                 goto again;
1672
1673         if (pages) {
1674                 for (i = 0; i < nrpages; i++) {
1675                         if (pages[i] == NULL)
1676                                 break;
1677                         __free_page(pages[i]);
1678                 }
1679                 OBD_FREE(pages, sizeof(*pages) * nrpages);
1680         }
1681         return rc;
1682 }
1683
1684 /* Copy a remote log locally */
1685 static int mgc_llog_local_copy(const struct lu_env *env,
1686                                struct obd_device *obd,
1687                                struct llog_ctxt *rctxt,
1688                                struct llog_ctxt *lctxt, char *logname)
1689 {
1690         char    *temp_log;
1691         int      rc;
1692
1693         ENTRY;
1694
1695         /*
1696          * - copy it to backup using llog_backup()
1697          * - copy remote llog to logname using llog_backup()
1698          * - if failed then move bakup to logname again
1699          */
1700
1701         OBD_ALLOC(temp_log, strlen(logname) + 2);
1702         if (!temp_log)
1703                 RETURN(-ENOMEM);
1704         sprintf(temp_log, "%sT", logname);
1705
1706         /* make a copy of local llog at first */
1707         rc = llog_backup(env, obd, lctxt, lctxt, logname, temp_log);
1708         if (rc < 0 && rc != -ENOENT)
1709                 GOTO(out, rc);
1710         /* copy remote llog to the local copy */
1711         rc = llog_backup(env, obd, rctxt, lctxt, logname, logname);
1712         if (rc == -ENOENT) {
1713                 /* no remote llog, delete local one too */
1714                 llog_erase(env, lctxt, NULL, logname);
1715         } else if (rc < 0) {
1716                 /* error during backup, get local one back from the copy */
1717                 llog_backup(env, obd, lctxt, lctxt, temp_log, logname);
1718 out:
1719                 CERROR("%s: failed to copy remote log %s: rc = %d\n",
1720                        obd->obd_name, logname, rc);
1721         }
1722         llog_erase(env, lctxt, NULL, temp_log);
1723         OBD_FREE(temp_log, strlen(logname) + 2);
1724         return rc;
1725 }
1726
1727 /* local_only means it cannot get remote llogs */
1728 static int mgc_process_cfg_log(struct obd_device *mgc,
1729                                struct config_llog_data *cld, int local_only)
1730 {
1731         struct llog_ctxt        *ctxt, *lctxt = NULL;
1732         struct client_obd       *cli = &mgc->u.cli;
1733         struct lustre_sb_info   *lsi = NULL;
1734         int                      rc = 0;
1735         bool                     sptlrpc_started = false;
1736         struct lu_env           *env;
1737
1738         ENTRY;
1739
1740         LASSERT(cld);
1741         LASSERT(mutex_is_locked(&cld->cld_lock));
1742
1743         /*
1744          * local copy of sptlrpc log is controlled elsewhere, don't try to
1745          * read it up here.
1746          */
1747         if (cld_is_sptlrpc(cld) && local_only)
1748                 RETURN(0);
1749
1750         if (cld->cld_cfg.cfg_sb)
1751                 lsi = s2lsi(cld->cld_cfg.cfg_sb);
1752
1753         OBD_ALLOC_PTR(env);
1754         if (env == NULL)
1755                 RETURN(-ENOMEM);
1756
1757         rc = lu_env_init(env, LCT_MG_THREAD);
1758         if (rc)
1759                 GOTO(out_free, rc);
1760
1761         ctxt = llog_get_context(mgc, LLOG_CONFIG_REPL_CTXT);
1762         LASSERT(ctxt);
1763
1764         lctxt = llog_get_context(mgc, LLOG_CONFIG_ORIG_CTXT);
1765
1766         /* Copy the setup log locally if we can. Don't mess around if we're
1767          * running an MGS though (logs are already local). */
1768         if (lctxt && lsi && IS_SERVER(lsi) && !IS_MGS(lsi) &&
1769             cli->cl_mgc_configs_dir != NULL &&
1770             lu2dt_dev(cli->cl_mgc_configs_dir->do_lu.lo_dev) ==
1771             lsi->lsi_dt_dev) {
1772                 if (!local_only)
1773                         /* Only try to copy log if we have the lock. */
1774                         rc = mgc_llog_local_copy(env, mgc, ctxt, lctxt,
1775                                                  cld->cld_logname);
1776                 if (local_only || rc) {
1777                         if (strcmp(cld->cld_logname, PARAMS_FILENAME) != 0 &&
1778                             llog_is_empty(env, lctxt, cld->cld_logname)) {
1779                                 LCONSOLE_ERROR_MSG(0x13a, "Failed to get MGS "
1780                                                    "log %s and no local copy."
1781                                                    "\n", cld->cld_logname);
1782                                 GOTO(out_pop, rc = -ENOENT);
1783                         }
1784                         CDEBUG(D_MGC, "Failed to get MGS log %s, using local "
1785                                "copy for now, will try to update later.\n",
1786                                cld->cld_logname);
1787                         rc = 0;
1788                 }
1789                 /* Now, whether we copied or not, start using the local llog.
1790                  * If we failed to copy, we'll start using whatever the old
1791                  * log has. */
1792                 llog_ctxt_put(ctxt);
1793                 ctxt = lctxt;
1794                 lctxt = NULL;
1795         } else {
1796                 if (local_only) /* no local log at client side */
1797                         GOTO(out_pop, rc = -EIO);
1798         }
1799
1800         if (cld_is_sptlrpc(cld)) {
1801                 sptlrpc_conf_log_update_begin(cld->cld_logname);
1802                 sptlrpc_started = true;
1803         }
1804
1805         /* logname and instance info should be the same, so use our
1806          * copy of the instance for the update.  The cfg_last_idx will
1807          * be updated here. */
1808         rc = class_config_parse_llog(env, ctxt, cld->cld_logname,
1809                                      &cld->cld_cfg);
1810         EXIT;
1811
1812 out_pop:
1813         __llog_ctxt_put(env, ctxt);
1814         if (lctxt)
1815                 __llog_ctxt_put(env, lctxt);
1816
1817         /*
1818          * update settings on existing OBDs. doing it inside
1819          * of llog_process_lock so no device is attaching/detaching
1820          * in parallel.
1821          * the logname must be <fsname>-sptlrpc
1822          */
1823         if (sptlrpc_started) {
1824                 LASSERT(cld_is_sptlrpc(cld));
1825                 sptlrpc_conf_log_update_end(cld->cld_logname);
1826                 class_notify_sptlrpc_conf(cld->cld_logname,
1827                                           strlen(cld->cld_logname) -
1828                                           strlen("-sptlrpc"));
1829         }
1830
1831         lu_env_fini(env);
1832 out_free:
1833         OBD_FREE_PTR(env);
1834         return rc;
1835 }
1836
1837 static bool mgc_import_in_recovery(struct obd_import *imp)
1838 {
1839         bool in_recovery = true;
1840
1841         spin_lock(&imp->imp_lock);
1842         if (imp->imp_state == LUSTRE_IMP_FULL ||
1843             imp->imp_state == LUSTRE_IMP_CLOSED)
1844                 in_recovery = false;
1845         spin_unlock(&imp->imp_lock);
1846
1847         return in_recovery;
1848 }
1849
1850 /**
1851  * Get a configuration log from the MGS and process it.
1852  *
1853  * This function is called for both clients and servers to process the
1854  * configuration log from the MGS.  The MGC enqueues a DLM lock on the
1855  * log from the MGS, and if the lock gets revoked the MGC will be notified
1856  * by the lock cancellation callback that the config log has changed,
1857  * and will enqueue another MGS lock on it, and then continue processing
1858  * the new additions to the end of the log.
1859  *
1860  * Since the MGC import is not replayable, if the import is being evicted
1861  * (rcl == -ESHUTDOWN, \see ptlrpc_import_delay_req()), retry to process
1862  * the log until recovery is finished or the import is closed.
1863  *
1864  * Make a local copy of the log before parsing it if appropriate (non-MGS
1865  * server) so that the server can start even when the MGS is down.
1866  *
1867  * There shouldn't be multiple processes running process_log at once --
1868  * sounds like badness.  It actually might be fine, as long as they're not
1869  * trying to update from the same log simultaneously, in which case we
1870  * should use a per-log semaphore instead of cld_lock.
1871  *
1872  * \param[in] mgc       MGC device by which to fetch the configuration log
1873  * \param[in] cld       log processing state (stored in lock callback data)
1874  *
1875  * \retval              0 on success
1876  * \retval              negative errno on failure
1877  */
1878 int mgc_process_log(struct obd_device *mgc, struct config_llog_data *cld)
1879 {
1880         struct lustre_handle lockh = { 0 };
1881         __u64 flags = LDLM_FL_NO_LRU;
1882         int rc = 0, rcl;
1883         bool retry = false;
1884         ENTRY;
1885
1886         LASSERT(cld != NULL);
1887
1888         /* I don't want multiple processes running process_log at once --
1889            sounds like badness.  It actually might be fine, as long as
1890            we're not trying to update from the same log
1891            simultaneously (in which case we should use a per-log sem.) */
1892 restart:
1893         mutex_lock(&cld->cld_lock);
1894         if (cld->cld_stopping) {
1895                 mutex_unlock(&cld->cld_lock);
1896                 RETURN(0);
1897         }
1898
1899         OBD_FAIL_TIMEOUT(OBD_FAIL_MGC_PAUSE_PROCESS_LOG, 20);
1900
1901         CDEBUG(D_MGC, "Process log %s:%p from %d\n", cld->cld_logname,
1902                cld->cld_cfg.cfg_instance, cld->cld_cfg.cfg_last_idx + 1);
1903
1904         /* Get the cfg lock on the llog */
1905         rcl = mgc_enqueue(mgc->u.cli.cl_mgc_mgsexp, LDLM_PLAIN, NULL,
1906                           LCK_CR, &flags, NULL, NULL, NULL,
1907                           cld, 0, NULL, &lockh);
1908         if (rcl == 0) {
1909                 /* Get the cld, it will be released in mgc_blocking_ast. */
1910                 config_log_get(cld);
1911                 rc = ldlm_lock_set_data(&lockh, (void *)cld);
1912                 LASSERT(rc == 0);
1913         } else {
1914                 CDEBUG(D_MGC, "Can't get cfg lock: %d\n", rcl);
1915
1916                 if (rcl == -ESHUTDOWN &&
1917                     atomic_read(&mgc->u.cli.cl_mgc_refcount) > 0 && !retry) {
1918                         struct obd_import *imp;
1919                         struct l_wait_info lwi;
1920                         int secs = cfs_time_seconds(obd_timeout);
1921
1922                         mutex_unlock(&cld->cld_lock);
1923                         imp = class_exp2cliimp(mgc->u.cli.cl_mgc_mgsexp);
1924
1925                         /* Let's force the pinger, and wait the import to be
1926                          * connected, note: since mgc import is non-replayable,
1927                          * and even the import state is disconnected, it does
1928                          * not mean the "recovery" is stopped, so we will keep
1929                          * waitting until timeout or the import state is
1930                          * FULL or closed */
1931                         ptlrpc_pinger_force(imp);
1932
1933                         lwi = LWI_TIMEOUT(secs, NULL, NULL);
1934                         l_wait_event(imp->imp_recovery_waitq,
1935                                      !mgc_import_in_recovery(imp), &lwi);
1936
1937                         if (imp->imp_state == LUSTRE_IMP_FULL) {
1938                                 retry = true;
1939                                 goto restart;
1940                         } else {
1941                                 mutex_lock(&cld->cld_lock);
1942                                 cld->cld_lostlock = 1;
1943                         }
1944                 } else {
1945                         /* mark cld_lostlock so that it will requeue
1946                          * after MGC becomes available. */
1947                         cld->cld_lostlock = 1;
1948                 }
1949                 /* Get extra reference, it will be put in requeue thread */
1950                 config_log_get(cld);
1951         }
1952
1953
1954         if (cld_is_recover(cld)) {
1955                 rc = 0; /* this is not a fatal error for recover log */
1956                 if (rcl == 0) {
1957                         rc = mgc_process_recover_log(mgc, cld);
1958                         if (rc != 0) {
1959                                 CERROR("%s: recover log %s failed: rc = %d"
1960                                        "not fatal.\n", mgc->obd_name,
1961                                        cld->cld_logname, rc);
1962                                 rc = 0;
1963                                 cld->cld_lostlock = 1;
1964                         }
1965                 }
1966         } else {
1967                 rc = mgc_process_cfg_log(mgc, cld, rcl != 0);
1968         }
1969
1970         CDEBUG(D_MGC, "%s: configuration from log '%s' %sed (%d).\n",
1971                mgc->obd_name, cld->cld_logname, rc ? "fail" : "succeed", rc);
1972
1973         mutex_unlock(&cld->cld_lock);
1974
1975         /* Now drop the lock so MGS can revoke it */
1976         if (!rcl) {
1977                 rcl = mgc_cancel(mgc->u.cli.cl_mgc_mgsexp, LCK_CR, &lockh);
1978                 if (rcl)
1979                         CERROR("Can't drop cfg lock: %d\n", rcl);
1980         }
1981
1982         RETURN(rc);
1983 }
1984
1985
1986 /** Called from lustre_process_log.
1987  * LCFG_LOG_START gets the config log from the MGS, processes it to start
1988  * any services, and adds it to the list logs to watch (follow).
1989  */
1990 static int mgc_process_config(struct obd_device *obd, size_t len, void *buf)
1991 {
1992         struct lustre_cfg *lcfg = buf;
1993         struct config_llog_instance *cfg = NULL;
1994         char *logname;
1995         int rc = 0;
1996         ENTRY;
1997
1998         switch(lcfg->lcfg_command) {
1999         case LCFG_LOV_ADD_OBD: {
2000                 /* Overloading this cfg command: register a new target */
2001                 struct mgs_target_info *mti;
2002
2003                 if (LUSTRE_CFG_BUFLEN(lcfg, 1) !=
2004                     sizeof(struct mgs_target_info))
2005                         GOTO(out, rc = -EINVAL);
2006
2007                 mti = (struct mgs_target_info *)lustre_cfg_buf(lcfg, 1);
2008                 CDEBUG(D_MGC, "add_target %s %#x\n",
2009                        mti->mti_svname, mti->mti_flags);
2010                 rc = mgc_target_register(obd->u.cli.cl_mgc_mgsexp, mti);
2011                 break;
2012         }
2013         case LCFG_LOV_DEL_OBD:
2014                 /* Unregister has no meaning at the moment. */
2015                 CERROR("lov_del_obd unimplemented\n");
2016                 rc = -ENOSYS;
2017                 break;
2018         case LCFG_SPTLRPC_CONF: {
2019                 rc = sptlrpc_process_config(lcfg);
2020                 break;
2021         }
2022         case LCFG_LOG_START: {
2023                 struct config_llog_data *cld;
2024                 struct super_block *sb;
2025
2026                 logname = lustre_cfg_string(lcfg, 1);
2027                 cfg = (struct config_llog_instance *)lustre_cfg_buf(lcfg, 2);
2028                 sb = *(struct super_block **)lustre_cfg_buf(lcfg, 3);
2029
2030                 CDEBUG(D_MGC, "parse_log %s from %d\n", logname,
2031                        cfg->cfg_last_idx);
2032
2033                 /* We're only called through here on the initial mount */
2034                 rc = config_log_add(obd, logname, cfg, sb);
2035                 if (rc)
2036                         break;
2037                 cld = config_log_find(logname, cfg);
2038                 if (cld == NULL) {
2039                         rc = -ENOENT;
2040                         break;
2041                 }
2042
2043                 /* COMPAT_146 */
2044                 /* FIXME only set this for old logs!  Right now this forces
2045                    us to always skip the "inside markers" check */
2046                 cld->cld_cfg.cfg_flags |= CFG_F_COMPAT146;
2047
2048                 rc = mgc_process_log(obd, cld);
2049                 if (rc == 0 && cld->cld_recover != NULL) {
2050                         if (OCD_HAS_FLAG(&obd->u.cli.cl_import->
2051                                          imp_connect_data, IMP_RECOV)) {
2052                                 rc = mgc_process_log(obd, cld->cld_recover);
2053                         } else {
2054                                 struct config_llog_data *cir = cld->cld_recover;
2055                                 cld->cld_recover = NULL;
2056                                 config_log_put(cir);
2057                         }
2058                         if (rc)
2059                                 CERROR("Cannot process recover llog %d\n", rc);
2060                 }
2061
2062                 if (rc == 0 && cld->cld_params != NULL) {
2063                         rc = mgc_process_log(obd, cld->cld_params);
2064                         if (rc == -ENOENT) {
2065                                 CDEBUG(D_MGC, "There is no params "
2066                                               "config file yet\n");
2067                                 rc = 0;
2068                         }
2069                         /* params log is optional */
2070                         if (rc)
2071                                 CERROR("%s: can't process params llog: rc = %d\n",
2072                                        obd->obd_name, rc);
2073                 }
2074                 config_log_put(cld);
2075
2076                 break;
2077         }
2078         case LCFG_LOG_END: {
2079                 logname = lustre_cfg_string(lcfg, 1);
2080
2081                 if (lcfg->lcfg_bufcount >= 2)
2082                         cfg = (struct config_llog_instance *)lustre_cfg_buf(
2083                                 lcfg, 2);
2084                 rc = config_log_end(logname, cfg);
2085                 break;
2086         }
2087         default: {
2088                 CERROR("Unknown command: %d\n", lcfg->lcfg_command);
2089                 GOTO(out, rc = -EINVAL);
2090
2091         }
2092         }
2093 out:
2094         RETURN(rc);
2095 }
2096
2097 static struct obd_ops mgc_obd_ops = {
2098         .o_owner        = THIS_MODULE,
2099         .o_setup        = mgc_setup,
2100         .o_precleanup   = mgc_precleanup,
2101         .o_cleanup      = mgc_cleanup,
2102         .o_add_conn     = client_import_add_conn,
2103         .o_del_conn     = client_import_del_conn,
2104         .o_connect      = client_connect_import,
2105         .o_disconnect   = client_disconnect_export,
2106         .o_set_info_async = mgc_set_info_async,
2107         .o_get_info       = mgc_get_info,
2108         .o_import_event = mgc_import_event,
2109         .o_process_config = mgc_process_config,
2110 };
2111
2112 static int __init mgc_init(void)
2113 {
2114         return class_register_type(&mgc_obd_ops, NULL, true, NULL,
2115                                    LUSTRE_MGC_NAME, NULL);
2116 }
2117
2118 static void __exit mgc_exit(void)
2119 {
2120         class_unregister_type(LUSTRE_MGC_NAME);
2121 }
2122
2123 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
2124 MODULE_DESCRIPTION("Lustre Management Client");
2125 MODULE_VERSION(LUSTRE_VERSION_STRING);
2126 MODULE_LICENSE("GPL");
2127
2128 module_init(mgc_init);
2129 module_exit(mgc_exit);