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