OSDN Git Service

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